2011-10-06 14 views
126

我想從Python調用外部程序。我用Popen()call()來做到這一點。子進程Popen和調用之間有什麼區別(我該如何使用它們)?

兩者有什麼區別?

我的具體目標是從Python運行以下命令。我不確定重定向是如何工作的。

./my_script.sh > output 

我讀the documentation和它說,call()是一個方便的功能或快捷功能。我們是否通過使用call()而不是Popen()失去了任何權力?

+0

文檔的哪些部分讓您困惑? 'call()'的定義似乎很清楚。你能提供一個報價或一個鏈接,所以我們知道在回答中需要關注什麼? –

回答

188

有兩種方法可以進行重定向。兩者適用於subprocess.Popensubprocess.call

  1. 設置關鍵字參數shell = Trueexecutable = /path/to/the/shell,並指定就像你有它存在的命令。

  2. 因爲你只是將輸出重定向到一個文件,設置關鍵字參數

    stdout = an_open_writeable_file_object 
    

    該對象指向output文件。

subprocess.Popensubprocess.call更一般。

Popen不會阻塞,允許您在流程運行時與流程交互,或者繼續處理Python程序中的其他內容。撥打Popen返回Popen對象。

call確實塊。雖然它支持與構造函數Popen相同的參數,但仍然可以設置進程的輸出,環境變量等,腳本將等待程序完成,並返回代表進程退出狀態的代碼。

returncode = call(*args, **kwargs) 

基本上與調用

returncode = Popen(*args, **kwargs).wait() 

call僅僅是一個方便的功能。這是一個在CPython的實現是在subprocess.py

def call(*popenargs, timeout=None, **kwargs): 
    """Run command with arguments. Wait for command to complete or 
    timeout, then return the returncode attribute. 

    The arguments are the same as for the Popen constructor. Example: 

    retcode = call(["ls", "-l"]) 
    """ 
    with Popen(*popenargs, **kwargs) as p: 
     try: 
      return p.wait(timeout=timeout) 
     except: 
      p.kill() 
      p.wait() 
      raise 

正如你可以看到,它的周圍Popen瘦包裝。

+7

基本上Popen和call是分別用異步和同步函數運行的Linux命令。 – user3016020

+1

使用popen的優點是什麼?等到被調用的程序第一次完成後不是安全的嗎? – Tom

+3

@湯姆通常不會。如果你想讀取一些輸出,然後發送更多的輸入到程序,讀取輸入的更多輸出,重複? – agf

相關問題