【问题标题】:grep/zgrep within python using subprocesspython中使用子进程的grep/zgrep
【发布时间】:2014-05-29 00:49:22
【问题描述】:

我有一组压缩成 *.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?

【问题讨论】:

  • 第一步是使用subprocess.check_output(['grep', string, tsvfile])

标签: python grep subprocess


【解决方案1】:

通过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_output 将引发异常。
  • check_output 从 Python 2.7 开始可用。换个角度看here

【讨论】:

    【解决方案2】:

    您的代码中的一些 cmets:

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

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

    接下来,如果您使用的是zgrep,则无需使用gzip.open 打开文件。您可以在 tsv.gz 文件上调用 zgrep,它会负责打开它,而无需您做任何额外的工作。所以改为尝试调用

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

    请注意,zgrep 也适用于未压缩的 tsv 文件,因此您无需在 grep 和 zgrep 之间不断切换。

    【讨论】:

      猜你喜欢
      • 2011-12-18
      • 1970-01-01
      • 2018-02-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-03
      • 1970-01-01
      相关资源
      最近更新 更多