czy istnieje sposób, aby uzyskać kod zwrotny bez try/z wyjątkiem?
check_output
podnosi wyjątek, jeśli otrzymuje niezerowy kod wyjścia, ponieważ często oznacza, że polecenie nie powiodło się. grep
może powrócić niezerowy kod zakończenia, nawet jeśli nie ma błędu - można użyć .communicate()
w tym przypadku:
from subprocess import Popen, PIPE
pattern, filename = 'test', 'tmp'
p = Popen(['grep', pattern, filename], stdin=PIPE, stdout=PIPE, stderr=PIPE,
bufsize=-1)
output, error = p.communicate()
if p.returncode == 0:
print('%r is found in %s: %r' % (pattern, filename, output))
elif p.returncode == 1:
print('%r is NOT found in %s: %r' % (pattern, filename, output))
else:
assert p.returncode > 1
print('error occurred: %r' % (error,))
Nie trzeba zadzwonić polecenie zewnętrzne do linii filtrów, można to zrobić w czysty Python:
with open('tmp') as file:
for line in file:
if 'test' in line:
print line,
Jeśli nie potrzebujesz wyjścia; można użyć subprocess.call()
:
import os
from subprocess import call
try:
from subprocess import DEVNULL # Python 3
except ImportError: # Python 2
DEVNULL = open(os.devnull, 'r+b', 0)
returncode = call(['grep', 'test', 'tmp'],
stdin=DEVNULL, stdout=DEVNULL, stderr=DEVNULL)
* "Google było żadnej pomocy" *: [pierwszy link] (http://stackoverflow.com/a/8235171/4279) (prawie nie pokazuje 'e. output'), [drugi link] (http://stackoverflow.com/a/15316680/4279) jest ** dokładnym dopasowaniem ** (pokazuje 'e.returncode') wyszukiwane hasło:' CalledProcessError'. – jfs