小编use*_*031的帖子

当grep找不到匹配项时,带有grep命令的subprocess.check_output失败

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

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

当文件包含grep标识的至少一行时,这可以正常工作.但是当grep没有标识任何行时,grep返回退出状态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
Run Code Online (Sandbox Code Playgroud)

我该如何避免这个问题?subprocess.check_output如果grep找不到任何内容,我只想返回一个空字符串.

谢谢

python grep subprocess

6
推荐指数
2
解决办法
6048
查看次数

标签 统计

grep ×1

python ×1

subprocess ×1