使用带有 cat 和多个进程管道的 popen 未获得 grep 结果

Posted

技术标签:

【中文标题】使用带有 cat 和多个进程管道的 popen 未获得 grep 结果【英文标题】:Not getting grep result using popen with cat and multiple process pipes 【发布时间】:2019-12-31 23:42:03 【问题描述】:

我正在尝试让 grep 使用管道和子进程工作。我已经仔细检查了猫,我知道它正在工作,但由于某种原因,grep 没有返回任何内容,即使当我通过终端运行它时,它也能正常工作。我想知道我是否正确构建了命令,因为它没有提供所需的输出,而且我不知道为什么。

我正在尝试从我已经从服务器检索到的文件中检索几行特定的数据。我在让 grep 工作方面遇到了很多问题,也许我不明白它是如何工作的。

p1 = subprocess.Popen(["cat", "result.txt"], stdout=subprocess.PIPE, 
stderr=subprocess.PIPE)
p2 = subprocess.Popen(["grep", "tshaper"], stdin=p1.stdout, 
stdout=subprocess.PIPE)
o = p1.communicate()
print(o)
p1.stdout.close()
out, err = p2.communicate()
print(out)

我在终端上运行此命令 (cat result.txt | grep "tshaper") 时的文件输出:

tshaper.1.devname=eth0 
tshaper.1.input.burst=0
tshaper.1.input.rate=25000
tshaper.1.input.status=enabled
tshaper.1.output.burst=0
tshaper.1.output.rate=25000
tshaper.1.output.status=enabled
tshaper.1.status=enabled
tshaper.status=disabled

我在脚本中运行命令的结果:

(b'', b'')

其中元组分别是p2进程的stdout、stderr。

编辑:

我将基于 Popen 文档的命令更改为

p1 = subprocess.Popen(['result.txt', 'cat'], shell=True, stdout=subprocess.PIPE,
                  stderr=subprocess.PIPE, cwd=os.getcwd())

到 p1 子进程语句。虽然我能够在 stderr 中获得输出,但它并没有真正改变任何东西,说

(b'', b'cat: 1: cat: result.txt: not found\n')

【问题讨论】:

【参考方案1】:

仅供参考:您收到此错误:(b'', b'cat: 1: cat: result.txt: not found\n'),因为您更改了 seq。 Popen 方法中的命令数:['result.txt', 'cat'](根据您的问题)。

我已经编写了一个可以提供预期输出的有效解决方案。

Python3.6.6已经被使用了。

result.txt 文件:

我更改了一些行来测试grep 命令。

tshaper.1.devname=eth0
ashaper.1.input.burst=0
bshaper.1.input.rate=25000
tshaper.1.input.status=enabled
tshaper.1.output.burst=0
cshaper.1.output.rate=25000
tshaper.1.output.status=enabled
dshaper.1.status=enabled
tshaper.status=disabled

代码:

我已经进行了可以理解的打印,但如果您只需要grep 的输出,则没有必要。 (在Python3中是一个类似bytesl的对象)

import subprocess

p1 = subprocess.Popen(['cat', 'result.txt'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
p2 = subprocess.check_output(["grep", "tshaper"], stdin=p1.stdout)
print("\n".join(p2.decode("utf-8").split(" ")))

输出:

您可以看到grep 按预期过滤来自cat 命令的行。

>>> python3 test.py 
tshaper.1.devname=eth0
tshaper.1.input.status=enabled
tshaper.1.output.burst=0
tshaper.1.output.status=enabled
tshaper.status=disabled

【讨论】:

以上是关于使用带有 cat 和多个进程管道的 popen 未获得 grep 结果的主要内容,如果未能解决你的问题,请参考以下文章

popen

可以python子进程Popen接受多个stdin流吗?

后台进程 subprocess.Popen 与管道

管道输出subprocess.Popen到文件

IPC通信基于管道的popen和pclose函数

带有标准输入的 subprocess.Popen.communicate() 的管道损坏