我试图用popen处理状态退出,但它给出了一个错误,代码是:
import os
try:
res = os.popen("ping -c 4 www.google.com")
except IOError:
print "ISPerror: popen"
try:
#wait = [0,0]
wait = os.wait()
except IOError:
print "ISPerror:os.wait"
if wait[1] != 0:
print(" os.wait:exit status != 0\n")
else:
print ("os.wait:"+str(wait))
print("before read")
result = res.read()
print ("after read:")
print ("exiting")
但是如果出现以下错误:
文件对象析构函数中关闭失败: IOError:[Errno 10]没有子进程
最佳答案
错误说明
看起来发生此错误是因为退出时,程序尝试销毁 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
,您可以将命令作为列表
字符串传递。能够access the output of the process ,您将 stdout
参数设置为 subprocess.PIPE
,这允许您稍后使用文件操作访问 stdout
。然后,subprocess.Popen
对象不使用常规的 os.wait()
方法,而是拥有自己的 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")
关于python - 处理退出状态 popen python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38689014/