1
votes

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!

2

2 Answers

1
votes

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

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