我有一个python脚本,通过几次检查。其中一项检查是通过对关键字执行grep并确认没有输出来确保结果不包含关键字。读取grep手册页的预期退出代码是1.但从用户角度来看,由于关键字不存在,所以通过检查。有没有办法,我可以返回退出状态0的grep与没有匹配命令,所以它不被视为异常或任何其他方式来处理它作为异常处理?注意用户将创建命令文件,所以我无法完全避免使用grep。Python supress grep不匹配退出状态
import subprocess
def cmd_test(command):
try:
cmd_output = subprocess.check_output(command,
stderr=subprocess.STDOUT,
shell=True,
timeout=120,
universal_newlines=False).decode('utf-8')
except subprocess.CalledProcessError as exc:
return (exc)
else:
return cmd_output.strip()
print(cmd_test('env | grep bash'))
print(cmd_test('env | grep test'))
print(cmd_test('env | grep bash'))
print(cmd_test('env | grep test'))
输出:
的grepSHELL=/bin/bash
Command 'env | grep test' returned non-zero exit status 1 b''
错误...只需检查异常对象中的退出代码?甚至直接使用'Popen'对象而不是'check_foo()' – o11c