là có một cách để có được một mã trở lại mà không có một thử/trừ?
check_output
tăng ngoại lệ nếu nó nhận được trạng thái thoát khác không vì nó thường có nghĩa là lệnh không thành công. grep
có thể trở lại khác không trạng thái thoát ngay cả khi không có lỗi - bạn có thể sử dụng .communicate()
trong trường hợp này:
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,))
Bạn không cần phải gọi một lệnh bên ngoài để dòng bộ lọc, bạn có thể làm điều đó trong tinh khiết Python:
with open('tmp') as file:
for line in file:
if 'test' in line:
print line,
Nếu bạn không cần đầu ra; bạn có thể sử dụng 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 đã không có sự giúp đỡ" *: [mắt xích đầu tiên] (http://stackoverflow.com/a/8235171/4279) (gần như có nó cho thấy 'e. output'), [liên kết thứ hai] (http://stackoverflow.com/a/15316680/4279) là ** đối sánh chính xác ** (nó hiển thị 'e.returncode') cụm từ tìm kiếm:' CalledProcessError'. – jfs