【问题标题】:How to get result from grep with Python如何使用 Python 从 grep 获取结果
【发布时间】:2019-01-24 06:24:43
【问题描述】:

我正在尝试使用通配符从 grep 获取输出

proc = subprocess.Popen(['grep', '002HQV', 'test.*'], stdout=subprocess.PIPE,  
shell=True)
res = proc.stdout.readlines()
print(res)

但出现以下错误

2.4.3 (#1, Jun 11 2009, 14:09:37)
[GCC 4.1.2 20080704 (Red Hat 4.1.2-44)]
Usage: grep [OPTION]... PATTERN [FILE]...  
Try `grep --help' for more information.
[]

我的 grep 语法有问题吗?

以下作品

proc = subprocess.Popen(['ls', '*'], stdout = subprocess.PIPE, shell=True)

os.system("grep 02HQV test.*")

【问题讨论】:

标签: python


【解决方案1】:

使用shell=True 时,您应该使用字符串,请参阅subprocess.call using string vs using list

您可以通过使用 glob 标准库模块来避免使用 shell 并仍然使用列表:

import subprocess
import glob

command = ['grep', '002HQV']
command.extend(glob.glob('test.*'))
proc = subprocess.Popen(command, stdout=subprocess.PIPE)
res = proc.stdout.readlines()
print(res)

【讨论】:

  • 但是如何解释proc = subprocess.Popen(['ls', '*'], stdout = subprocess.PIPE, shell=True) 有效?
  • @HsingYi - * 被忽略,它与subprocess.Popen(['ls'], stdout = subprocess.PIPE, shell=True) 相同。 ls 的默认值是当前目录.* shell 扩展是当前目录下的所有文件名,这两者都是你得到的。
【解决方案2】:

一般来说,我会尽量避免为简单的字符串操作和简单的文件 I/O 启动子进程。当你开始接触像subprocess.call(shell=True) 这样的危险事物时尤其如此。您可以使用glob module 进行文件名扩展,然后循环文件。

这是一个例子:

import glob
res = []
for fn in glob.glob('test.*'):
    with open(fn, 'r') as f:
        for line in f:
          if '002HQV' in line:
              res.append(line)
print(res)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-28
    • 2016-09-11
    • 1970-01-01
    • 2011-04-10
    • 2022-11-25
    相关资源
    最近更新 更多