錯誤解釋
它看起來像這樣的錯誤是在退出,因爲發生,親克試圖破壞res
,其中涉及調用res.close()
方法。但不知何故,調用os.wait()
已經關閉了該對象。所以它試圖關閉res
兩次,導致錯誤。如果除去對os.wait()
的呼叫,則不再發生錯誤。
import os
try:
res = os.popen("ping -c 4 www.google.com")
except IOError:
print "ISPerror: popen"
print("before read")
result = res.read()
res.close() # explicitly close the object
print ("after read: {}".format(result)
print ("exiting")
但是這會讓您知道何時該流程已經完成。而且由於res
只是有型號file
,您的選擇是有限的。我反而轉移到使用subprocess.Popen
使用subprocess.Popen
要使用subprocess.Popen
,你作爲一個字符串的list
通過你的命令。爲了能夠access the output of the process,您將stdout
參數設置爲subprocess.PIPE
,它允許您稍後使用文件操作訪問stdout
。然後,代替使用常規os.wait()
方法,subprocess.Popen
對象有自己的wait
方法直接調用對象,這也代表退出狀態的sets the returncode
值。
import os
import subprocess
# list of strings representing the command
args = ['ping', '-c', '4', 'www.google.com']
try:
# stdout = subprocess.PIPE lets you redirect the output
res = subprocess.Popen(args, stdout=subprocess.PIPE)
except OSError:
print "error: popen"
exit(-1) # if the subprocess call failed, there's not much point in continuing
res.wait() # wait for process to finish; this also sets the returncode variable inside 'res'
if res.returncode != 0:
print(" os.wait:exit status != 0\n")
else:
print ("os.wait:({},{})".format(res.pid, res.returncode)
# access the output from stdout
result = res.stdout.read()
print ("after read: {}".format(result))
print ("exiting")
使用'subprocess.Popen()'來代替:https://docs.python.org/2/library/subprocess.html#replacing-os-popen-os-popen2-os-popen3 –