cmd模块 - python

时间:2016-09-02 11:02:36

标签: python shell cmd subprocess

我正在尝试使用cmd模块构建一个python shell。

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。我正在尝试构建这两个功能。

欢迎来到shell

平台> ls

平台> cd ..

就像我想表演一样 ls - 在我的python shell中列出该目录中的所有文件 要么 cd .. - 回到prev目录

有人可以帮忙吗? 我尝试使用子进程库..但没有让它工作。

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

2 个答案:

答案 0 :(得分:0)

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

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方法捕获作为输入传递的所有命令。

答案 1 :(得分:-2)

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

在命令行中:

(Cmd)!ls
(Cmd)!pwd
相关问题