如何终止由 Python Popen 创建的进程 [英] How to terminate process created by Python Popen

查看:49
本文介绍了如何终止由 Python Popen 创建的进程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 proc = subprocess.Popen("calc.exe") 运行 calc.exe(windows 10,python 3.6),然后使用 time.sleep(time) 然后想杀死进程: os.kill(proc.pid, -9)os.kill(proc.pid, signal.SIGTERM) 给我错误

I'm running calc.exe (windows 10, python 3.6) using proc = subprocess.Popen("calc.exe"), then time.sleep(time) and then want to kill process: os.kill(proc.pid, -9) or os.kill(proc.pid, signal.SIGTERM) gives me error

拒绝访问".

我也试过 proc.terminate - 它没有帮助.

I also tried proc.terminate - it didn't help.

而且我还注意到 proc.pid 给出了与任务管理器中显示的 PID 不同的 PID.任何想法如何终止我的进程?

And I also noticed that proc.pid gives different PID from PID which is shown in task manager. Any ideas how to kill my process?

谢谢!

推荐答案

您可以尝试使用 windows 杀死进程.

You can try using windows to kill the process.

command = "Taskkill /IM calc.exe /F"
proc = subprocess.Popen(command)

import os
os.system("taskkill /im Calculator.exe /f")

如果你想确定,试试递归杀死!!

If you want to be sure., Try a recursive kill!!

def kill_process(proc):
    # Check process is running, Kill it if it is,

    # Try to kill the process - 0 exit code == success

    kill = "TaskKill /IM {} /F".format(proc)

    res = subprocess.run(kill)

    if res == 0:
        return True  # Process Killed
    else:
        kill_process(proc)  # Process not killed repeat until it is!

kill_process('Calculator.exe')

这篇关于如何终止由 Python Popen 创建的进程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆