How to terminate process created by Python Popen

半腔热情 提交于 2021-02-10 14:27:53

问题


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

"Access Denied".

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

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?

Thanks!


回答1:


You can try using windows to kill the process.

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

or

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')



回答2:


In the python 3 subprocess API, one can kill the child by calling

Popen.kill()

which is an alias for Popen.terminate() in Windows (see here). If this doesn't work, you can try

os.system("TASKKILL /F /PID [child PID]")

You can get the PID of the child with Popen.pid()



来源:https://stackoverflow.com/questions/51325685/how-to-terminate-process-created-by-python-popen

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!