我试图用 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
To use subprocess.Popen
,您将命令作为list
字符串。有能力去访问进程的输出,您设置stdout
论证subprocess.PIPE
,它允许您访问stdout
稍后使用文件操作。然后,不使用常规的os.wait()
方法,subprocess.Popen
物体有自己的wait
直接在对象上调用的方法,这也是设置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")
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)