Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I close the CMD window that opened with subprocess.Popen in Python?

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
like image 952
KaramJaber Avatar asked Nov 29 '17 08:11

KaramJaber


People also ask

Does Popen need to be closed?

Popen do we need to close the connection or subprocess automatically closes the connection? Usually, the examples in the official documentation are complete. There the connection is not closed. So you do not need to close most probably.

How do I close a command window in Python?

Python exit commands: quit(), exit(), sys. exit() and os. _exit()

How do you stop a subprocess run in Python?

To close a single subprocess in Python, use the kill() method. The kill() is a built-in method used for terminating a single subprocess. The kill() command keeps running in the background.

Does subprocess Popen block?

Popen is nonblocking. call and check_call are blocking. You can make the Popen instance block by calling its wait or communicate method.


2 Answers

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

like image 144
Jean-François Fabre Avatar answered Nov 04 '22 15:11

Jean-François Fabre


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)
like image 26
pankaj mishra Avatar answered Nov 04 '22 14:11

pankaj mishra