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