2016-07-31 122 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")