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