我想知道subprocess.call()
已正確終止,沒有任何錯誤的被調用函數。例如,在下面的代碼,如果所提供的路徑是不恰當的,則ls
命令給出爲錯誤:如何檢查子進程是否正確終止?
ERROR:No such file or directory.
我想相同的輸出值被存儲爲字符串。
import subprocess
path = raw_input("Enter the path")
subprocess.call(["ls","-l",path])
我想知道subprocess.call()
已正確終止,沒有任何錯誤的被調用函數。例如,在下面的代碼,如果所提供的路徑是不恰當的,則ls
命令給出爲錯誤:如何檢查子進程是否正確終止?
ERROR:No such file or directory.
我想相同的輸出值被存儲爲字符串。
import subprocess
path = raw_input("Enter the path")
subprocess.call(["ls","-l",path])
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
你不能做到這一點與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。
類似的問題已經被問。 http://stackoverflow.com/questions/1996518/retrieving-the-output-of-subprocess-call – 2014-12-13 10:57:39
@GeorgeSimms:通常輸出和退出狀態是不同的東西。只要知道返回代碼而不檢索子進程stdout/stderr就可以了,無論stdout/stderr的值如何,檢查子進程是否正常終止,例如非零退出狀態通常表示錯誤(取決於子進程)。 – jfs 2014-12-16 16:10:24
@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