2016-07-31 96 views
1

我特林处理与POPEN状态退出,但它给出了一个错误,代码:处理退出状态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") 

但是,如果给了以下错误:

关闭失败文件对象的析构: IO错误:[错误10]无子进程

+1

使用'subprocess.Popen()'来代替:https://docs.python.org/2/library/subprocess.html#replacing-os-popen-os-popen2-os-popen3 –

回答

1

错误解释

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