我有这个简单的示例代码片段,它基本上对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:资源警告:子进程 1519 仍在运行">
由于我的代码等同于 https://docs.python.org/3.8/library/subprocess.html#replacing-shell-pipeline,所以我很确定要做正确的事情。那么为什么会生成此警告,或者我可以做些什么来防止 python 在那里抱怨(除了抑制警告(?
你缺少(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