错误解释
它看起来像这样的错误是在退出,因为发生,亲克试图破坏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 –