我有一个文件夹,里面有很多像file_1.gz到file_250.gz这样的文件,而且还在增加。
搜索它们的zgrep命令类似于:
zgrep -Pi "\"name\": \"bob\"" ../../LM/DATA/file_*.gz我想在python子进程中执行这个命令,如下所示:
out_file = os.path.join(out_file_path, file_name)
search_command = ['zgrep', '-Pi', '"name": "bob"', '../../LM/DATA/file_*.gz']
process = subprocess.Popen(search_command, stdout=out_file)问题是创建了out_file,但是它是空的,并且引发了以下错误:
<type 'exceptions.AttributeError'>
'str' object has no attribute 'fileno'解决办法是什么?
发布于 2015-10-31 09:42:23
您需要传递一个文件对象:
process = subprocess.Popen(search_command, stdout=open(out_file, 'w'))引用手册,强调我的观点:
stdin、stdout和stderr分别指定执行程序的标准输入、标准输出和标准错误文件句柄。有效值是管道、现有文件描述符(正整数)、现有文件对象和None。管道表示应该为子管道创建一个新管道。默认设置为None时,不会发生重定向;子文件句柄将从父进程继承。
结合LFJ的回答--建议使用方便的函数,您需要使用shell=True来使通配符(*)工作:
subprocess.call(' '.join(search_command), stdout=open(out_file, 'w'), shell=True)
或者当您使用shell时,也可以使用shell重定向:
subprocess.call("%s > %s" % (' '.join(search_command), out_file), shell=True)
发布于 2015-10-31 16:51:50
有两个问题:
.fileno()方法而不是文件名传递一些东西。*,但除非您询问,否则子进程不会调用shell。您可以使用glob.glob()手动展开文件模式。示例:
#!/usr/bin/env python
import os
from glob import glob
from subprocess import check_call
search_command = ['zgrep', '-Pi', '"name": "bob"']
out_path = os.path.join(out_file_path, file_name)
with open(out_path, 'wb', 0) as out_file:
check_call(search_command + glob('../../LM/DATA/file_*.gz'),
stdout=out_file)发布于 2015-10-31 10:15:31
如果希望执行shell命令并获取输出,请尝试使用subprocess.check_output()。它非常简单,您可以轻松地将输出保存到文件中。
command_output = subprocess.check_output(your_search_command, shell=True)
with open(out_file, 'a') as f:
f.write(command_output)https://stackoverflow.com/questions/33450106
复制相似问题