Can I close the CMD window that opened with subpro

2019-07-04 06:14发布

问题:

I have a program that need to run small tasks in new CMDs. For example:

def main()
    some code
    ...
    proc = subprocess.Popen("start.bat")
    some code...
    proc.kill()

subprocess,Popen opens a new cmd window and runs "start.bat" in it. proc.kill() kills the process but doesn't close the cmd window. Is there a way to close this cmd window?

I thought about naming the opened cmd window so i can kill it with the command:

/taskkill /f /im cmdName.exe

Is it possible ?if no, What do you suggest ?

Edit, Added Minimal, Complete, and Verifiable example:

a.py:

import subprocess,time
proc = subprocess.Popen("c.bat",creationflags=subprocess.CREATE_NEW_CONSOLE)
time.sleep(5)
proc.kill()

b.py

while True:
    print("IN")

c.bat

python b.py

回答1:

that's expected when a subprocess is running. You're just killing the .bat process.

You can use psutil (third party, use pip install psutil to install) to compute the child processes & kill them, like this:

import subprocess,time,psutil
proc = subprocess.Popen("c.bat",creationflags=subprocess.CREATE_NEW_CONSOLE)
time.sleep(5)

pobj = psutil.Process(proc.pid)
# list children & kill them
for c in pobj.children(recursive=True):
    c.kill()
pobj.kill()

tested with your example, the window closes after 5 seconds



回答2:

here is another way you can do it

import subprocess
from subprocess import Popen,CREATE_NEW_CONSOLE
command ='cmd'
prog_start=Popen(command,creationflags=CREATE_NEW_CONSOLE)
pidvalue=prog_start.pid
#this will kill the invoked terminal
subprocess.Popen('taskkill /F /T /PID %i' % pidvalue)