首页 > 解决方案 > Killing shell=True 进程导致 ResourceWarning: subprocess is still running

问题描述

遵循如何终止使用 shell=True 启动的 python 子进程的建议

我有一个从以下开始的过程

process = subprocess.Popen(my_cmd, shell=True, executable='/bin/bash', preexec_fn=os.setsid)

my_cmd 的形式为some_cmd_that_periodically_outputs_to_stdout | grep "some_fancy_regex" > some_output_file.txt

我用以下命令杀死了这个过程

os.killpg(os.getpgid(process.pid), signal.SIGKILL)

杀死后,我收到以下警告

ResourceWarning: subprocess XXX is still running

为什么我会收到此警告?

标签: pythonsubprocess

解决方案


你没有wait让这个过程结束。即使你杀死了这个进程,你仍然应该wait这样做,这样你就不会有一个僵尸进程。Python 警告你,你没有wait

process.wait()杀死它后添加一个呼叫。


推荐阅读