cmd模块python

2024-04-26 13:44:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我尝试使用cmd模块构建一个pythonshell。在

from cmd import Cmd
import subprocess
import commands
import os 
from subprocess import call

class Pirate(Cmd): 
    intro = 'Welcome to shell\n'
    prompt = 'platform> '
    pass

if __name__ == '__main__':
    Pirate().cmdloop()

我尝试使用python-cmd模块构建一个shell。我正在尝试构建这两个功能。在

欢迎来到壳牌

平台>;ls

平台>;cd。。在

如果我想表演 ls-列出pythonshell中该目录下的所有文件 或 cd。。-返回上一个目录

有人能帮忙吗? 我试着用子程序库。。但没有起作用。在

感谢你的帮助! 参考文件:https://docs.python.org/3/library/cmd.html


Tags: 模块文件fromimportgt目录cmdcd
2条回答

我很难弄清楚你为什么需要这样的东西,但我的尝试是:

import subprocess
from cmd import Cmd

class Pirate(Cmd): 
    intro = 'Welcome to shell\n'
    prompt = 'platform> '

    def default(self, line): # this method will catch all commands
        subprocess.call(line, shell=True)

if __name__ == '__main__':
    Pirate().cmdloop()

要点是使用default方法捕获作为输入传递的所有命令。在

def do_shell(self, line):
    "Run a shell command"
    print "running shell command:", line
    sub_cmd = subprocess.Popen(line,shell=True,stdout=subprocess.PIPE)
    output = sub_cmd.communicate()[0]
    print output
    self.last_output = output

在命令行中:

^{pr2}$

相关问题 更多 >