How to destroy an .exe file(not converted from

2019-08-16 01:57发布

问题:

I have a script that runs an .exe file via subprocess.Popen(), but I just realized, that .exe file keeps running even I close my script. Is there any way to stop running an .exe file via name of it or ID? That exe file is not converted from a py file, so I'm stuck.

回答1:

If you run process = subprocess.Popen(...) then you could terminate the process later using process.terminate().

If the subprocess may create its own children then process.terminate() and/or process.kill() might not be enough. On Windows, you might need to create a Job object and assign the .exe process to it. On Unix, you could use start_new_session=True (preexec_fn=os.setsid or preexec_fn=os.setpgrp on earlier Python versions) plus os.pgkill(process.pid, signal.SIGINT) to kill processes belonging to the same process group (or prctl(PR_SET_PDEATHSIG, ...) on Linux, to send a signal when the parent dies). See

  • How to terminate a python subprocess launched with shell=True
  • Python: how to kill child process(es) when parent dies?

See also, killableprocess.py