2015-10-04 51 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鏈接 –

相關問題