使用命令模拟 shell

问题描述 投票:0回答:1

我正在制作一个不和谐的机器人,作为机器人的一部分,我想创建模拟 shell 的选项(允许用户在机器人的主机上运行 ls、cd 等命令)。我尝试从Python文档中学习如何使用subprocess,并提出了这个类:

class CommandLine:
    def __init__(self, command: str):
       self.process = subprocess.Popen(command, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    
    def run(self):
       self.process.wait()
       # some processes don't have an exit code, so i check if there's an error instead
       if len(self.process.stderr) == 0:
           return self.process.stdout
       else:
           return self.process.stderr

    def close(self):
       self.process.stdin.close()

此类适用于一次运行一个命令,但我无法链接依赖于先前命令的多个命令(例如,无法使用依赖于当前目录的任何命令,因为 cd 不执行任何操作)。我怎样才能一个接一个地运行多个命令,而不为每个命令创建一个新的子进程?

注意:由于我的目标只是模拟 shell,所以我并不真正关心正在使用的模块。如果有更好的模块或方法来做这件事,我更愿意使用它

python subprocess
1个回答
0
投票

并不是针对每种情况的最佳解决方案,但我决定单独运行每个命令,并为影响系统本身的任何内容创建函数:

class CommandLine:
    def __init__(self):
        self.dir = os.getcwd()
    
    def run(self, command: str):
        result = subprocess.run(command, shell=True, check=True, capture_output=True)
        if len(result.stderr) == 0:
            return result.stdout
        else:
            return result.stderr
    
    def cd(self, new: str):
        # here should be the code for the cd command
        ...

我知道这不是最好的解决方案,因为我需要为我想使用的每个命令创建一个新函数,但它完成了工作,而且因为这只是一个小的不和谐机器人,所以我不介意这个。

© www.soinside.com 2019 - 2024. All rights reserved.