gnc*_*ncc 5 python windows subprocess
我使用的是 Windows 10 和 Python 3.7。
我运行了以下命令。
import subprocess
exeFilePath = "C:/Users/test/test.exe"
subprocess.run(exeFilePath)
Run Code Online (Sandbox Code Playgroud)
使用此命令启动的 .exe 文件,我想在单击按钮或执行函数时强制退出。
查看过去的问题,有人指出强制退出的方法是获取PID并执行OS.kill,如下所示。
import signal
os.kill(self.p.pid, signal.CTRL_C_EVENT)
Run Code Online (Sandbox Code Playgroud)
但是,我不知道如何获取在 subprocess.run 中启动的进程的 PID。
我应该怎么办?
将变量分配给您的子流程
\n\nimport os\nimport signal\nimport subprocess\n\nexeFilePath = "C:/Users/test/test.exe"\np = subprocess.Popen(exeFilePath)\nprint(p.pid) # the pid\nos.kill(p.pid, signal.SIGTERM) #or signal.SIGKILL \nRun Code Online (Sandbox Code Playgroud)\n\n在相同情况下,进程有子进程。您需要杀死所有进程才能终止它。在这种情况下你可以使用psutil
#python -m pip install \xe2\x80\x94user psutil \n\nimport psutil\n\n#remember to assign subprocess to a variable \n\ndef kills(pid):\n \'\'\'Kills all process\'\'\'\n parent = psutil.Process(pid)\n for child in parent.children(recursive=True):\n child.kill()\n parent.kill()\n\n#assumes variable p\nkills(p.pid)\nRun Code Online (Sandbox Code Playgroud)\n\n这将杀死该 PID 中的所有进程
\n