有没有办法在没有尝试/例外的情况下获得返回码?
check_output 如果收到非零退出状态,则会引发异常,因为这通常意味着命令失败。即使没有错误,grep 也可能返回非零退出状态——在这种情况下,您可以使用 .communicate():
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,))
您不需要调用外部命令来过滤行,您可以在纯 Python 中完成:
with open('tmp') as file:
for line in file:
if 'test' in line:
print line,
如果你不需要输出;你可以使用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)