2

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

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

thanks! But why proc.pid gives the value which differs from the PID in task manager?
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') 

9 Comments

OK, thanks! I'll try it on Monday and will write you my result. P.S, i've just tried to execute the code i've written on Windows 7 with proc.terminate() and it works! Do you know why it doesn't on Win10?
Probably something to do with user access rights..Maybe try running the script as admin. I had the same problem on windows 10 and had to write this function that does the job..
It didn't help. A saw in the Task Manager that process was created with the name "Calculator.exe" (not calc.exe). I tried to implement "proc.terminate()" once more - it workswithout errors but when script terminates, calculator is still working:(
What happens if you run TaskKill /IM calc.exe /F from cmd? (Also try Calculator.exe)
Calculator.exe - terminates successfully, calc.exe gives error: windows can't find such process
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.