2009-04-14 183 views

回答

17

要從Python調用外部程序,請使用subprocess模塊。

子流程模塊允許您產生新的進程,連接到它們的輸入/輸出/錯誤管道,並獲得它們的返回代碼。

從DOC的一個例子(output是一個文件對象,它提供從子過程的輸出。):

output = subprocess.Popen(["mycmd", "myarg"], stdout=PIPE).communicate()[0] 

一個具體的例子,使用cmd,Windows命令行解釋器以2個參數:

>>> p1 = subprocess.Popen(["cmd", "/C", "date"],stdout=subprocess.PIPE) 
>>> p1.communicate()[0] 
'The current date is: Tue 04/14/2009 \r\nEnter the new date: (mm-dd-yy) ' 
>>> 
+0

我可以使用os.popen()嗎? – Kim 2009-04-14 15:25:55

+0

不,不要使用os.popen(),它已被子進程廢棄。 – unwind 2009-04-14 15:27:37

6

我敢肯定,你在這裏談論的Windows(根據你的問題的措辭),但在Unix/Linux操作系統(包括Mac)的環境下,命令MODUL e是也是可用的:

import commands 

(stat, output) = commands.getstatusoutput("somecommand") 

if(stat == 0): 
    print "Command succeeded, here is the output: %s" % output 
else: 
    print "Command failed, here is the output: %s" % output 

的命令模塊提供了一個非常簡單的接口來運行命令和獲取狀態(返回代碼)和輸出(從stdout和stderr閱讀)。或者,您可以分別通過調用commands.getstatus()或commands.getoutput()來獲得狀態或僅輸出。