使用子进程在python中使用grep/zgrep

2024-09-28 22:21:16 发布

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

我有一套压缩的TSV。广州tsv格式和一些未压缩的文件,如目录中的*.tsv。在

我想从这些文件中获取一个字符串,并在一个新行中打印grep结果。在

我有一个函数,它在输入目录中输入tsv和*。广州tsv存储和要搜索的字符串。在

import sys, os, traceback,subprocess,gzip,glob
def filter_from_tsvs(input_dir,string):

    tsvs = glob.glob(os.path.join(input_dir,'*.tsv*'))
    open_cmd=open
    for tsvfile in tsvs:
        print os.path.splitext
        extension = os.path.splitext(tsvfile)[1]
        if extension == ".gz":
          open_cmd = gzip.open
    print open_cmd
    try:
        print subprocess.check_output('grep string tsvfile', shell=True)

    except Exception as e:
        print "%s" %e
        print "%s" %traceback.format_exc()
return

我还尝试使用:

^{pr2}$

我得到这个错误: gzip: tsvfile.gz: No such file or directory Command 'zgrep pbuf tsvfile' returned non-zero exit status 2 Traceback (most recent call last): File "ex.py", line 23, in filter_from_maintsvs print subprocess.check_output('zgrep pbuf tsvfile', shell=True) File "/datateam/tools/opt/lib/python2.7/subprocess.py", line 544, in check_output raise CalledProcessError(retcode, cmd, output=output) CalledProcessError: Command 'zgrep pbuf tsvfile' returned non-zero exit status 2

如何在python中使用grep/zgrep?
提前谢谢你的帮助。在


Tags: pathincmdoutputtsvosopengrep
2条回答

对代码的一些注释:

现在,您已经将要查找的字符串和文件名硬编码为“string”和“tsvfile”。试试这个:

subprocess.check_output(['grep', string, tsvfile])

接下来,如果使用zgrep,则不需要使用gzip.open打开文件。您可以对tsv.gz文件调用zgrep,它将负责打开它,而不需要您做任何额外的工作。所以试着打电话

^{pr2}$

请注意,zgrep也可以处理未压缩的tsv文件,因此不需要在grep和zgrep之间切换。在

在经历了blog之后,我得到了以下解决方案:)

import subprocess
import signal

output = subprocess.check_output('grep string tsvfile', shell=True, preexec_fn=lambda: signal.signal(signal.SIGPIPE, signal.SIG_DFL))

print output  

提示:

  • 如果找不到字符串,grep以退出代码1结尾,check\u输出将引发异常。在
  • check_输出从python2.7开始就可用了。另一种外观here。在

相关问题 更多 >