2014-12-13 76 views
1

我想知道subprocess.call()已正確終止,沒有任何錯誤的被調用函數。例如,在下面的代碼,如果所提供的路徑是不恰當的,則ls命令給出爲錯誤:如何檢查子進程是否正確終止?

ERROR:No such file or directory.

我想相同的輸出值被存儲爲字符串。

import subprocess 
path = raw_input("Enter the path") 
subprocess.call(["ls","-l",path]) 
+1

類似的問題已經被問。 http://stackoverflow.com/questions/1996518/retrieving-the-output-of-subprocess-call – 2014-12-13 10:57:39

+0

@GeorgeSimms:通常輸出和退出狀態是不同的東西。只要知道返回代碼而不檢索子進程stdout/stderr就可以了,無論stdout/stderr的值如何,檢查子進程是否正常終止,例如非零退出狀態通常表示錯誤(取決於子進程)。 – jfs 2014-12-16 16:10:24

+0

@JFSebastian作者詢問 - 子進程是否成功(可以根據退出代碼的錯誤來確定) - 將子進程輸出爲stdout/stderr作爲字符串(可以通過調用'communicate '對Popen的結果) 'subprocess.call'不足,因爲無法檢索到stdout/stderr的輸出。否則,我們可以做'something_went_wrong()如果subprocess.call(stuff)else we_are_ok()' – 2014-12-16 21:09:28

回答

1
from subprocess import Popen, PIPE 
p = Popen(["ls", "-l", path], stdin=PIPE, stdout=PIPE, stderr=PIPE) 
output, err = p.communicate() 
status = p.returncode 
if status: 
    # something went wrong 
    pass 
else: 
    # we are ok 
    pass 

雖然考慮使用os.listdir

+0

您不需要讀取輸出,以檢查成功狀態。獲得退出狀態;存儲'subprocess.call()'返回值(一個整數)就足夠了。非零狀態在許多情況下意味着錯誤。輸出可以被重定向到DEVNULL,以避免噪聲,例如'stderr = DEVNULL'。 – jfs 2014-12-16 16:08:35

+0

@ J.F.Sebastian OP明確表示想要讀取輸出。 – BartoszKP 2014-12-16 17:55:22

+0

@BartoszKP:我知道。該評論是針對因其標題而登錄該網頁的人。 – jfs 2014-12-16 18:02:09

0

你不能做到這一點與call,因爲他們做的僅僅是:

Run the command described by args. Wait for command to complete, then return the returncode attribute.

所以你只能確定一個程序,這通常意味着零,如果沒有發生錯誤的返回碼,和否則不爲零。

從相同的模塊使用check_output方法:

try: 
    result = subprocess.check_output(["ls", "-l", path], 
            stderr = subprocess.STDOUT) 
    print result 
except subprocess.CalledProcessError, e: 
    print "Error:", e.output 

這裏是一個working demo

+0

我不明白downvotes。該方法清楚地起作用並且使用爲此目的而記錄的方法。 – BartoszKP 2014-12-13 11:00:28

+0

可能是因爲check_output不是正在使用的調用,您可能會使用check_call – 2014-12-13 11:05:34

+0

@PadraicCunningham您不能在這裏使用'check_call',因爲它不會以字符串形式返回輸出。與'call'類似,它只返回一個錯誤代碼。 – BartoszKP 2014-12-13 11:07:45