How to stop command prompt from closing in python?

On windows, it's the CMD console that closes, because the Python process exists at the end.

To prevent this, open the console first, then use the command line to run your script. Do this by right-clicking on the folder that contains the script, select Open console here and typing in python scriptname.py in the console.

The alternative is, as you've found out, to postpone the script ending by adding a input() call at the end. This allows the user of the script to choose when the script ends and the console closes.


That can be done with os module. Following is the simple code :

import os
os.system("pause")

This will generate a pause and will ask user to press any key to continue.

[edit: The above method works well for windows os. It seems to give problem with mac (as pointed by ihue, in comments). The thing is that "os" library is operating system specific and some commands might not work with one operating system like they work in another one.]


For Windows Environments:

If you don't want to go to the command prompt (or work in an environment where command prompt is restricted), I think the following solution is gooThe solution I use is to create a bat file.

Use notepad to create a text file. In the file the contents will look something like:

my_python_program.py pause

Then save the file as "my_python_program.bat" - DO NOT FORGET TO SELECT "All Files!

When you run the bat file it will run the python program and pause at the end to allow you to read the output. Then if you press any key it will close the window.