2015-10-04 198 views
-1

我正在尝试使用模块python cmd编写一个python CLI程序。当我尝试在我的CLI程序中执行另一个python脚本时,我的目标是在其他文件夹中的其他文件夹和CLI程序中有一些python脚本。我正在尝试使用CLI程序来执行这些python脚本。os.popen如何使用参数externaly来运行另一个脚本

下面是用于执行其他有脚本的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命令行程序 1 = cmd – Create line-oriented command processors 2 = Console built with Cmd object (Python recipe)

和一些屏幕快照的更多信息: enter image description here

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

+0

如果任何人都可以有想法。如何解决这个请发布你的程序..这是非常有助于我的工作 –

+0

执行其他脚本,我也已经尝试sys.system()如果你有想法解决这个与os.system()请发布。 .. –

+0

确定对不起导入系统我是删除这个时候发布我的程序。 –

回答

1

如DOC规定:

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() 
+0

正确阅读文档。 do_shell(self,line,args):这里是参数的参数。 –

+0

这个链接是你引用的正确文档:https://pymotw.com/2/cmd/index.html – idjaw

+0

我发布在我的quastion链接 –

相关问题