एक मामूली संशोधन @ SvenMarnach के कोड है कि मानक आउटपुट धारा को मुद्रण के मुद्दे को संबोधित करने के लिए: py स्क्रिप्ट, कि एक "जो" पार मंच कार्यान्वयन है। यदि आप subprocess.call()
के बजाय subprocess.check_output()
फ़ंक्शन का उपयोग करते हैं तो आप स्ट्रिंग को अपने कोड में मानक रूप से मुद्रित करने वाली स्ट्रिंग को नियंत्रित कर सकते हैं और अभी भी अपवाद और निकास स्थिति कोड पकड़ सकते हैं।
आप टर्मिनल में मानक आउटपुट धारा को दबाने के लिए, स्ट्रिंग कि check_output
से दिया जाता है एसटीडी प्रिंट आउट नहीं करना चाहते हैं:
import subprocess
import os
try:
stdout_string = subprocess.check_output(["wget", "--help"], stderr=subprocess.STDOUT)
# print(stdout_string)
except subprocess.CalledProcessError as cpe:
print(cpe.returncode)
print(cpe.output)
except OSError as e:
if e.errno == os.errno.ENOENT:
print(e)
else:
# Something else went wrong while trying to run `wget`
print(e)
गैर शून्य से बाहर निकलें स्थिति कोड और आउटपुट स्ट्रिंग उठाए गए हैं CalledProcessError
में subprocess.CalledProcessError.returncode
और subprocess.CalledProcessError.output
के रूप में ताकि आप जो कुछ भी चाहें कर सकें।
आप, टर्मिनल के लिए निष्पादन योग्य के मानक आउटपुट मुद्रित स्ट्रिंग है जो दिया जाता है प्रिंट करना चाहते हैं:
import subprocess
import os
try:
stdout_string = subprocess.check_output(["wget", "--help"], stderr=subprocess.STDOUT)
print(stdout_string)
except subprocess.CalledProcessError as cpe:
print(cpe.returncode)
print(cpe.output)
except OSError as e:
if e.errno == os.errno.ENOENT:
print(e)
else:
# Something else went wrong while trying to run `wget`
print(e)
print()
स्ट्रिंग के लिए एक अतिरिक्त न्यू लाइन कहते हैं। आप (जैसा कि ऊपर) प्रिंट (के साथ दिखाया गया बयान और बाहर एसटीडी स्ट्रीम के बजाय एसटीडी अं धारा के मानक त्रुटि बारे में) है कि खत्म करने के लिए चाहते हैं, sys.stdout.write(string)
और sys.stderr.write(string)
बजाय प्रिंट() का उपयोग करें:
import subprocess
import os
import sys
try:
stdout_string = subprocess.check_output(["bogus"], stderr=subprocess.STDOUT)
sys.stdout.write(stdout_string)
except subprocess.CalledProcessError as cpe:
sys.stderr.write(cpe.returncode)
sys.stderr.write(cpe.output)
except OSError as e:
if e.errno == os.errno.ENOENT:
sys.stderr.write(e.strerror)
else:
# Something else went wrong while trying to run `wget`
sys.stderr.write(e.strerror)
स्रोत
2014-01-07 22:05:56
के संभावित डुप्लिकेट [टेस्ट निष्पादन मौजूद रहने पर पायथन में?] (http://stackoverflow.com/questions/377017/test-if-executable-exists-in-python) –