【发布时间】: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