【问题标题】:cmd module - pythoncmd模块-python
【发布时间】:2017-01-10 11:27:21
【问题描述】:

我正在尝试使用 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

【问题讨论】:

  • 你这样做有什么理由吗?我的意思是创建新的外壳?
  • 是的..对于我们的项目,我们将通过这个自动化一些脚本..我只是想在去那些之前尝试这些
  • 你尝试过使用带有钩子的 ipython 吗?
  • 您打算在 Python 中重新实现所有命令,例如 lscd,还是只想调用底层系统命令?
  • Guillaume - 我只是想了解一下 python shell 的工作原理,并有兴趣尝试这些东西。

标签: python shell cmd subprocess


【解决方案1】:

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

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

【讨论】:

  • 你能告诉我它如何与任何系统命令如 ls / cd 一起工作
  • 您作为输入传递的任何命令(例如ls -lh /)都将传递给default(line) 方法。 subprocess.call(line) 将简单地调用此命令行(通过使用给定参数启动适当的进程)。如果 ls 在您的 PATH 中,那将起作用。
  • 我没有让它工作 :( 我运行程序并在 python shell 中尝试了 ls。platform> ls platform> cd .. 也没有成功
【解决方案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

【讨论】:

  • 就目前而言,您的答案很难阅读。您可以通过正确格式化和缩进代码来清理它吗?此外,如果您添加更多文本来解释您的代码是如何工作的,也会有所帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2010-10-20
  • 2021-09-10
  • 1970-01-01
  • 1970-01-01
  • 2017-08-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多