I am using subprocess.Popen
in order to run some executable from the CMD shell:
p = subprocess.Popen('cmd /c start app.exe')
I am having problems closing the console window when killing CMD via p.terminate()
. If I do it right away, then the console window doesn't even open. If I do it after some time, then the console window doesn't close.
The app.exe
that CMD runs is a server, listening to some other process. When that other process is done, I need to close the server along with the console window to which it is attached.
I believe that p
is in fact a handle to the start app.exe
batch script, and not to the actual CMD shell.
Here is my full script:
import subprocess
p1 = subprocess.Popen('cmd /c start app.exe')
p2 = subprocess.Popen('cmd /c call test.exe')
p2.wait()
p1.terminate()
I have also tried this (based on this answer):
import subprocess, psutil
p1 = subprocess.Popen('cmd /c start app.exe')
p2 = subprocess.Popen('cmd /c call test.exe')
p2.wait()
pobj = psutil.Process(p1.pid)
pobj.terminate()
But got a NoSuchProcess
exception.
From some of the answers that I've found on similar questions, I think it can be done by the title of the window, but I would really like to avoid this clumsy workaround.