执行zgrep命令并将结果写入fi

2024-09-28 22:24:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个文件夹,里面有很多文件,比如file_1.gz到{},而且还在增加。在

搜索它们的zgrep命令如下:

zgrep -Pi "\"name\": \"bob\"" ../../LM/DATA/file_*.gz

我希望在python子进程中执行此命令,例如:

^{pr2}$

{cd4>产生的问题是空的:

<type 'exceptions.AttributeError'>
'str' object has no attribute 'fileno'

解决办法是什么?在


Tags: 文件name命令文件夹data进程typepi
3条回答

您需要传递一个file对象:

process = subprocess.Popen(search_command, stdout=open(out_file, 'w'))

引用manual,强调我的:

stdin, stdout and stderr specify the executed program’s standard input, standard output and standard error file handles, respectively. Valid values are PIPE, an existing file descriptor (a positive integer), an existing file object, and None. PIPE indicates that a new pipe to the child should be created. With the default settings of None, no redirection will occur; the child’s file handles will be inherited from the parent.

结合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)

如果要执行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)

有两个问题:

  1. 您应该使用有效的.fileno()方法而不是文件名来传递内容
  2. shell展开*,但子进程不会调用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)

相关问题 更多 >