Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/310.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用Python从grep中获取结果_Python - Fatal编程技术网

如何使用Python从grep中获取结果

如何使用Python从grep中获取结果,python,Python,我正在尝试使用通配符从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 [

我正在尝试使用通配符从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)


使用
shell=True
时,应使用字符串,请参阅

通过使用
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)

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

这里有一个例子:

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)

可能重复的但如何解释
proc=subprocess.Popen(['ls','*',stdout=subprocess.PIPE,shell=True)
有效?@xingyi-忽略
*
,它与
subprocess.Popen(['ls',stdout=subprocess.PIPE,shell=True)相同。
ls
的默认值是当前目录
*
shell扩展是当前目录中的所有文件名,这是您在这两个目录中都可以得到的文件名。
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)