-1

我正在尝试使用模块 python cmd 编写一个 python CLI 程序。当我尝试在我的 CLI 程序中执行另一个 python 脚本时,我的目标是在其他文件夹中有一些 python 脚本,在其他文件夹中有 CLI 程序。我正在尝试使用 CLI 程序执行那些 python 脚本。

下面是用于执行其他脚本的 os.popen 方法有 CLI 程序:

import cmd
import os
import sys

class demo(cmd.Cmd):

   def do_shell(self,line,args):
     """hare is function to execute the other script"""
    output = os.popen('xterm -hold -e python %s' % args).read()
    output(sys.argv[1])

def do_quit(self,line):

    return True

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

野兔是错误的:

(Cmd) shell demo-test.py
Traceback (most recent call last):
File "bemo.py", line 18, in <module>
demo().cmdloop()
File "/usr/lib/python2.7/cmd.py", line 142, in cmdloop
stop = self.onecmd(line)
File "/usr/lib/python2.7/cmd.py", line 221, in onecmd
return func(arg)
TypeError: do_shell() takes exactly 3 arguments (2 given)

有一些到其他 cmd CLI 程序的链接 1 = cmd – 创建面向行的​​命令处理器 2 =使用 Cmd 对象构建的控制台(Python 配方)

以及一些屏幕截图以获取更多信息: 在此处输入图像描述

请在您的系统中运行上述代码。

4

1 回答 1

1

如文档中所述:

https://pymotw.com/2/cmd/index.html

do_shell 定义如下:

do_shell(self, args):

但是您将其定义为

do_shell(self, line, args):

我认为预期用途是按照文档中的规定定义它。

我运行了您的代码并按照您的示例进行操作。我复制了你的错误。然后,按照 do_shell 文档中的说明,我将方法更改为预期的:

do_shell(self, args):

从那里,sys模块丢失了,所以你也需要导入它(除非你没有从源代码复制它)。在那之后,我得到一个索引超出范围的错误,可能是因为期望需要传递额外的参数。

此外,因为您在谈论 Python 脚本,所以我认为您不需要添加额外的命令,我只是将这一行更改为:

output = os.popen('python %s' % args).read()

但是,如果有特殊原因需要 xterm 命令,那么您可以将其放回去,它适用于您的特定情况。

我也没有看到这个用例:

output(sys.argv[1])

我把它注释掉了。我运行了你的代码,一切正常。我创建了一个测试文件,它只是做了一个简单的打印,它运行成功。

所以,代码实际上是这样的:

def do_shell(self, args):
    """hare is function to execute the other script"""
    output = os.popen('python %s' % args).read()
    print output

完整的代码应如下所示:

import cmd
import os
import sys

class demo(cmd.Cmd):

    def do_shell(self, args):
        """hare is function to execute the other script"""
        output = os.popen('python %s' % args).read()
        print output

    def do_quit(self,line):

        return True

if __name__ == '__main__':
    demo().cmdloop()
于 2015-10-04T19:35:47.277 回答