python - 处理退出状态 popen python

标签 python

我试图用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/

相关文章:

Python - 如何将此时间戳格式转换为日期时间?

找不到 Python linalg 包?

python - 声音与音乐的区别

python - 时间戳数组的年份与今天的差异

Python 和 Numpy nan 和 set

python - pycrypto - 长度不正确的密文

python - 查找一个数据帧的哪些行存在于另一个数据帧中

python - 使用 DTD 从 Sax 到 Dom (python)

python - 在 python 中对字典进行排序并将结果作为字典返回

python - 从多行记录创建 Spark 数据结构