Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python to close own CMD shell window on exit

I am running multiple processes (hundreds), each of which is in python and invoked using:

command = 'start cmd /k call python %s' % (some_py_prog)
os.system(command)

where the /k leaves the cmd window open after execution. This is good to inspect for errors. However, as I call hundreds of jobs, my screen gets cluttered.

How then to make python close its own host cmd window on successful completion only? I need the errored jobs to remain visible.

like image 921
SteveBuk Avatar asked Oct 22 '17 10:10

SteveBuk


People also ask

How do I exit command prompt shell?

At the command prompt, type exit. Depending on the device configuration, you may be presented with another menu, for example: Access selection menu: a: Admin CLI s: Shell q: Quit Select access or quit [admin] : Type q or quit to exit.

How do I close a command window in Python?

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

How do I exit Python shell in Terminal?

Ensure that you are running the correct version of Python (at least Python 3). If you are on a Mac you can also check the version you are running by typing python3 -version in Terminal. You will then see the shell prompt >>> indicating that you are in the Python shell. To exit the python shell, simply enter exit().


1 Answers

Short answer: just use /c instead of /k will cause the cmd script to exit as soon as the command terminates, which is what you ask for:

command = 'start cmd /c call python %s' % (some_py_prog)
os.system(command)

But you are stacking some unnecessary cmd.exe here: one for the os.system call, one for the explicit cmd.c. You could simply use the subprocess module:

subprocess.call('python %s' % (some_py_prog), 
    creationflags = subprocess.CREATE_NEW_CONSOLE)

The creation flag is enough to ask the system to start the new process in a new console that will be closed as soon as the command will be terminated. Optionaly, you can add the shell=True option if you need it to pre-process some cmd goodies like io redirection.

(more details in that other answer from mine, specially in eryksun's comment)

like image 143
Serge Ballesta Avatar answered Sep 28 '22 08:09

Serge Ballesta