【发布时间】: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')
【问题讨论】:
标签: python-3.x grep subprocess popen cat