2013-03-09 7 views
19

उठाता है तो मैं कमांड के रिटर्न कोड की जांच करता हूं, मैं एक पाइथन (3) स्क्रिप्ट में शेल कमांड की stdout स्ट्रीम को कैप्चर करना चाहता हूं, और साथ ही, खोल के रिटर्न कोड को चेक करने के लिए सक्षम होना चाहता हूं आदेश अगर यह एक त्रुटि देता है (यानी, अगर इसका रिटर्न कोड 0 नहीं है)।जब कोई सबप्रोसेस कॉलडप्रोसेसर अपवाद

subprocess.check_output ऐसा करने के लिए उपयुक्त तरीका प्रतीत होता है। subprocess के आदमी पृष्ठ से:

check_output(*popenargs, **kwargs) 
    Run command with arguments and return its output as a byte string. 

    If the exit code was non-zero it raises a CalledProcessError. The 
    CalledProcessError object will have the return code in the returncode 
    attribute and output in the output attribute. 

फिर भी, मैं जब यह विफल शेल कमांड से वापसी कोड प्राप्त करने के लिए सफल नहीं है। मेरे कोड इस तरह दिखता है:

import subprocess 
failing_command=['ls', 'non_existent_dir'] 

try: 
    subprocess.check_output(failing_command) 
except: 
    ret = subprocess.CalledProcessError.returncode # <- this seems to be wrong 
    if ret in (1, 2): 
     print("the command failed") 
    elif ret in (3, 4, 5): 
     print("the command failed very much") 

इस कोड को अपवाद ही की हैंडलिंग में एक अपवाद को जन्म देती है:

Traceback (most recent call last): 
    File "<stdin>", line 4, in <module> 
AttributeError: type object 'CalledProcessError' has no attribute 'returncode' 

मैं मानता हूं मैं नहीं जानता कि मैं कहाँ गलत हूँ।

from subprocess import Popen, PIPE 

p = Popen(["ls", "non existent"], stdout=PIPE) 
output = p.communicate()[0] 
print(p.returncode) 

subprocess.CalledProcessError एक वर्ग है:

उत्तर

33

दोनों प्रक्रिया उत्पादन और लौट आए कोड प्राप्त करने के लिए। returncode उपयोग अपवाद उदाहरण पहुंचने के लिए:

from subprocess import CalledProcessError, check_output 

try: 
    output = check_output(["ls", "non existent"]) 
    returncode = 0 
except CalledProcessError as e: 
    output = e.output 
    returncode = e.returncode 

print(returncode) 
+0

आपको बहुत बहुत धन्यवाद, यह एक तरह काम करता है आकर्षण :) – michaelmeyer

2

सबसे अधिक संभावना मेरा उत्तर प्रासंगिक नहीं रह गया है, लेकिन मैं इसे इस कोड के साथ हल किया जा सकता है:

import subprocess 
failing_command='ls non_existent_dir' 

try: 
    subprocess.check_output(failing_command, shell=True, stderr=subprocess.STDOUT) 
except subprocess.CalledProcessError as e: 
    ret = e.returncode 
    if ret in (1, 2): 
     print("the command failed") 
    elif ret in (3, 4, 5): 
     print("the command failed very much") 
संबंधित मुद्दे