2017-08-25 106 views
0

我有一个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')) 

输出:

的grep
SHELL=/bin/bash 
Command 'env | grep test' returned non-zero exit status 1 b'' 
+0

错误...只需检查异常对象中的退出代码?甚至直接使用'Popen'对象而不是'check_foo()' – o11c

回答

1

实施例不匹配之后返回的出口1,正常行为:

$ env | grep test 
$ echo $? 
1 

抑制的grep的返回值和强制为0退出状态的实施例:

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

试试这个。希望能帮助到你。

+0

您可以使用'! '运营商喜欢这里:https://stackoverflow.com/questions/367069/how-can-i-negate-the-return-value-of-a-process – Arminius