【发布时间】:2016-01-31 17:05:48
【问题描述】:
我有一个文件夹,其中包含许多文件,例如 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'
解决办法是什么?
【问题讨论】:
-
你真的需要在这里使用
subprocess吗?为什么不直接使用os.walk()获取该文件夹中的所有文件,然后使用正则表达式搜索您想要的文件? -
其实,如果要对所有文件运行相同的命令,根本不需要python。
find ../../LM/DATA -name 'file*.gz' | xargs zgrep -Pi '"name": "bob"'。如果要并行运行它,只需使用GNU parallel而不是xargs。 -
原因是代码和平是一个大项目的一部分,它搜索日志文件,然后将结果返回给客户端
标签: python file shell command subprocess