[英]cmd module - python
我正在尝试使用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模块构建外壳。 我正在尝试构建这两个功能。
欢迎来到壳牌
平台> ls
平台> cd ..
就像我要执行ls-在python shell或cd中列出该目录中的所有文件。-返回上一个目录
有人可以帮忙吗? 我尝试使用子进程库..但没有使其工作。
感谢您的帮助 ! 参考文档: https : //docs.python.org/3/library/cmd.html
我很难弄清楚为什么您会需要这样的东西,但这是我的尝试:
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
在命令行中:
(Cmd)!ls
(Cmd)!pwd
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.