【问题标题】:How can os.popen take argument externaly to run another scriptos.popen 如何从外部获取参数来运行另一个脚本
【发布时间】:2015-10-05 04:13:18
【问题描述】:

我正在尝试使用模块 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 – Create line-oriented command processors 2 = Console built with Cmd object (Python recipe)

还有一些屏幕截图以获取更多信息:

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

【问题讨论】:

  • 如果有人有想法。如何解决这个问题请发布你的程序..这对我的工作很有帮助
  • 执行其他脚本,我也已经尝试过 sys.system() 如果你想用 os.system() 解决这个问题,请发布...
  • 好的抱歉导入系统我在发布我的程序时删除它。
  • 是的,在新的 xterm 中执行 python 脚本...你能帮帮我吗

标签: python python-2.7 subprocess ubuntu-14.04 python-os


【解决方案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()

【讨论】:

  • 正确阅读文档。 do_shell(self,line,args):这里的 args 用于参数。
  • 此链接是否是您引用的正确文档:pymotw.com/2/cmd/index.html
  • 我在我的 quastion 中发布链接
  • @NajeebChoudhary 告诉我你的想法。我更新了我的答案
  • 您的缩进已关闭。确保所有空间都正确对齐。不要混用制表符/空格。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-12-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-10-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多