当grep找不到匹配项时,使用grep命令的subprocess.check_输出失败

2024-05-23 18:52:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图搜索一个文本文件并检索包含一组特定单词的行。这是我正在使用的代码:

tyrs = subprocess.check_output('grep "^A" %s | grep TYR' % pocket_location, shell = True).split('\n')

当文件包含grep标识的至少一行时,此操作可以正常工作。但是当grep没有标识任何行时,grep返回exit status 1,我得到以下错误:

Traceback (most recent call last):
  File "../../Python_scripts/cbs_wrapper2.py", line 324, in <module>
    tyrs = subprocess.check_output('grep "^ATOM" %s | grep TYR' % pocket_location, shell = True).split('\n')
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 544, in check_output
    raise CalledProcessError(retcode, cmd, output=output)
subprocess.CalledProcessError: Command 'grep "^ATOM" cbsPrediction_files/1u9c_clean/1u9c_clean_fpocket_out/pockets/pocket0_atm.pdb | grep TYR' returned non-zero exit status 1

我怎样才能避免这个问题?我只希望subprocess.check_output在grep找不到任何内容时返回空字符串。

谢谢


Tags: trueoutputcheckstatusexitlocationshellgrep
2条回答

I just want subprocess.check_output to return an empty string if grep doesn't find anything.

好吧,太糟了。^{}认为没有匹配项是失败的,而^{}check的整个要点是检查失败,所以您明确要求这样做。以下是相关文件:

If the return code was non-zero it raises a CalledProcessError. The CalledProcessError object will have the return code in the returncode attribute and any output in the output attribute.

对于grep

The following exit values shall be returned:
  0 One or more lines were selected.
  1 No lines were selected.
  >1 An error occurred.

因此,如果要将“无行”视为成功,而将实际错误视为错误,则必须以不同于其他非零值的方式处理该1值。而且check_output不知道你想这么做。

所以,要么你必须处理CalledProcessError,要么你必须自己检查。换句话说,要么这样:

try:
    tyrs = subprocess.check_output('grep "^A" %s | grep TYR' % pocket_location, shell = True).split('\n')
except subprocess.CalledProcessError as e:
    if e.returncode > 1:
        raise
    tyrs = []

……或者这个:

p = subprocess.Popen('grep "^A" %s | grep TYR' % pocket_location, shell=True,
                     stdout=subprocess.PIPE)
output, _ = p.communicate()
if p.returncode == 1: # no matches found 
    tyrs = []
elif p.returncode == 0: # matches found
    tyrs = output.split('\n')
else:
    # error, do something with it
tyrs = subprocess.check_output('grep "^A" %s | grep TYR || true' % pocket_location, shell = True).split('\n')

相关问题 更多 >