如何正确完成(管道)python子进程

时间:2019-12-22 13:12:32

标签: python subprocess

我有这个小例子代码片段,它基本上对python子进程执行了ls | grep foo

import subprocess
import warnings

warnings.simplefilter("always")

lhs = subprocess.Popen(["ls"], stdout=subprocess.PIPE)
rhs = subprocess.Popen(["grep", "foo"], stdin=lhs.stdout)
lhs.stdout.close()
rhs.communicate()

最后,我收到一条警告:

“ / usr / lib / python3.8 / subprocess.py:942:ResourceWarning:子进程1519仍在运行”

由于我的代码等效于https://docs.python.org/3.8/library/subprocess.html#replacing-shell-pipeline,因此我敢肯定做对了。那么为什么会生成此警告,或者我该怎么做以防止python在那里抱怨(除了抑制警告)?

1 个答案:

答案 0 :(得分:1)

您遗漏了 lhs.communicate() lhs.wait()communicate还等待过程完成,但是wait更具解释性),

lhs = subprocess.Popen(["ls"], stdout=subprocess.PIPE)
rhs = subprocess.Popen(["grep", "foo"], stdin=lhs.stdout)
lhs.stdout.close()
rhs.communicate()
lhs.wait()

但是IMO,您应该使用更高级别的功能,例如subprocess.run