0

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.

GLHF
  • 3,835
  • 10
  • 38
  • 83
  • 1
    Have you tried killing the process? `proc = subprocess.Popen(...)`, wrap the code in a try/finally calling `proc.kill()` – Padraic Cunningham Jun 09 '16 at 23:23
  • proc.kill("anexe.exe") like this? – GLHF Jun 09 '16 at 23:29
  • I mean just call `proc.kill()` , I am not overly familiar with windows but if I say started vlc using a subprocess, if I wanted to kill it I would just call proc.kill() or proc.terminate() depending on how exactly I wanted it to stop – Padraic Cunningham Jun 09 '16 at 23:33
  • @GLHF, no, just `proc.kill()`, if `proc` is the name to which you assigned the `Popen` object, exactly as Padraic said. – Charles Duffy Jun 09 '16 at 23:56

1 Answers1

0

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

See also, killableprocess.py

Community
  • 1
  • 1
jfs
  • 399,953
  • 195
  • 994
  • 1,670