【问题标题】:How to get the pid of the process started by subprocess.run and kill it如何获取由 subprocess.run 启动的进程的 pid 并杀死它
【发布时间】:2020-05-28 14:00:47
【问题描述】:

我使用的是 Windows 10 和 Python 3.7。

我运行了以下命令。

import subprocess
exeFilePath = "C:/Users/test/test.exe"
subprocess.run(exeFilePath)

用这个命令启动的.exe文件,我想在点击按钮或执行函数时强制退出。

Looking at a past question,已经指出强制退出的方法是获取PID,然后执行OS.kill,如下所示。

import signal
os.kill(self.p.pid, signal.CTRL_C_EVENT)

但是,我不知道如何在 subprocess.run 中获取启动进程的 PID。

我该怎么办?

【问题讨论】:

  • 没有意义,因为run是一个阻塞调用。所以惯用的方式是不使用run而是创建一个子进程,然后使用kill或者terminate就可以了。
  • 这能回答你的问题吗? How to terminate process from Python using pid?

标签: python windows subprocess


【解决方案1】:

为您的子流程分配一个变量

import os
import signal
import subprocess

exeFilePath = "C:/Users/test/test.exe"
p = subprocess.Popen(exeFilePath)
print(p.pid) # the pid
os.kill(p.pid, signal.SIGTERM) #or signal.SIGKILL 

在相同的情况下,该进程有子进程 过程。您需要杀死所有进程才能终止它。在这种情况下,您可以使用psutil

#python -m pip install —user psutil 

import psutil

#remember to assign subprocess to a variable 

def kills(pid):
    '''Kills all process'''
    parent = psutil.Process(pid)
    for child in parent.children(recursive=True):
        child.kill()
    parent.kill()

#assumes variable p
kills(p.pid)

这将杀死该 PID 中的所有进程

【讨论】:

  • 感谢您回答我的问题。但是,我收到以下错误。 AttributeError: 'CompletedProcess' object has no attribute 'pid'.
  • 代替subprocess.run,你可以试试subprocess.Popen吗?
  • 我能够以这种方式启动并获取 pid。谢谢。
  • 看来run, call 没有返回pid。
  • Windows 不维护进程树。进程只存储其父进程的 PID,这允许孤立进程。杀死所有子进程的唯一可靠方法是在 kill-on-close Job 对象中运行该进程。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-09-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-06-29
  • 2013-02-07
相关资源
最近更新 更多