问题
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