【发布时间】:2018-02-03 01:22:41
【问题描述】:
我有一个运行多个检查的 python 脚本。其中一项检查是通过对关键字执行 grep 并确认没有输出来确保结果不包含关键字。阅读 grep 手册页,预期的退出代码是 1。但从用户的角度来看,检查通过了,因为关键字不存在。有没有一种方法可以在没有匹配命令的情况下为 grep 返回退出状态 0,因此它不会作为异常处理或任何其他方式来避免将其作为异常处理?注意用户将创建命令文件,所以我不能完全避免使用 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'))
输出:
SHELL=/bin/bash
Command 'env | grep test' returned non-zero exit status 1 b''
【问题讨论】:
-
Err ... 只是检查异常对象中的退出代码?甚至直接使用
Popen对象而不是check_foo()
标签: python bash return-code