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

问题描述 投票:0回答:1

我有这个小例子代码片段,它基本上对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在那里抱怨(除了抑制警告)?

python subprocess
1个回答
0
投票

您缺少lhs.communicate()

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

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

© www.soinside.com 2019 - 2024. All rights reserved.