【问题标题】:Python supress grep no match exit statusPython 抑制 grep 不匹配退出状态
【发布时间】: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


【解决方案1】:

grep 在不匹配后返回退出 1 的示例,正​​常行为:

$ env | grep test
$ echo $?
1

抑制 grep 的返回值并强制为 0 退出状态的示例:

$ env | { grep test || true; }
$ echo $?
0

试试这个。希望对您有所帮助。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2011-09-02
  • 2022-11-10
  • 2014-06-18
  • 2018-09-18
  • 2020-08-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多