在python中使用子进程Grep /zgrep



我有一组以*.tsv.gz格式压缩的tsv和一些未压缩的tsv,即*。

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

我有一个函数,它查找存储tsvs和*.tsv.gz的输入目录以及要搜索的字符串。

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

我也试过使用:

         try:
             fname = open_cmd(tsvfile,"r")
             print "opened"
             print subprocess.check_output('grep string fname', shell=True)

我得到这个错误:

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 ?

我在浏览了一个博客后得到了以下解决方案,它对我有效:)

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_output将引发异常。
  • check_output从Python 2.7开始可用。

代码注释:

此刻你已经硬编码字符串和文件名你正在寻找'string'和'tsvfile'。试试这个:

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

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

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

请注意,zgrep也可以在未压缩的tsv文件上工作,所以您不需要在grep和zgrep之间不断切换。

最新更新