Use the -i Flag to Stop the Python Program From Closing Immediately. The -i flag is used to set the inspect flag to True when used in the command prompt. This prevents the program from exiting on SystemExit , so it can solve a Python program from closing immediately.
Challenge: Run a piece of Python code forever—until it is forcefully interrupted by the user. Solution: use a while loop with a Boolean expression that always evaluates to True . Examples: have a look at the following variants of an infinite while loop.
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.
Output is displayed in the Shell window.
You have a few options:
Run the program from an already-open terminal. Open a command prompt and type:
python myscript.py
For that to work you need the python executable in your path. Just check on how to edit environment variables on Windows, and add C:\PYTHON26
(or whatever directory you installed python to).
When the program ends, it'll drop you back to the cmd prompt instead of closing the window.
Add code to wait at the end of your script. For Python2, adding ...
raw_input()
... at the end of the script makes it wait for the Enter key. That method is annoying because you have to modify the script, and have to remember removing it when you're done. Specially annoying when testing other people's scripts. For Python3, use input()
.
Use an editor that pauses for you. Some editors prepared for python will automatically pause for you after execution. Other editors allow you to configure the command line it uses to run your program. I find it particularly useful to configure it as "python -i myscript.py
" when running. That drops you to a python shell after the end of the program, with the program environment loaded, so you may further play with the variables and call functions and methods.
cmd /k
is the typical way to open any console application (not only Python) with a console window that will remain after the application closes. The easiest way I can think to do that, is to press Win+R, type cmd /k
and then drag&drop the script you want to the Run dialog.
Start the script from already open cmd window or at the end of script add something like this, in Python 2:
raw_input("Press enter to exit ;)")
Or, in Python 3:
input("Press enter to exit ;)")
To keep your window open in case of exception (yet, while printing the exception)
if __name__ == '__main__':
try:
## your code, typically one function call
except Exception:
import sys
print sys.exc_info()[0]
import traceback
print traceback.format_exc()
print "Press Enter to continue ..."
raw_input()
To keep the window open in any case:
if __name__ == '__main__':
try:
## your code, typically one function call
except Exception:
import sys
print sys.exc_info()[0]
import traceback
print traceback.format_exc()
finally:
print "Press Enter to continue ..."
raw_input()
For Python3 you'll have to use input()
in place of raw_input()
, and of course adapt the print
statements.
if __name__ == '__main__':
try:
## your code, typically one function call
except BaseException:
import sys
print(sys.exc_info()[0])
import traceback
print(traceback.format_exc())
print("Press Enter to continue ...")
input()
To keep the window open in any case:
if __name__ == '__main__':
try:
## your code, typically one function call
except BaseException:
import sys
print(sys.exc_info()[0])
import traceback
print(traceback.format_exc())
finally:
print("Press Enter to continue ...")
input()
you can combine the answers before: (for Notepad++ User)
press F5 to run current script and type in command:
cmd /k python -i "$(FULL_CURRENT_PATH)"
in this way you stay in interactive mode after executing your Notepad++ python script and you are able to play around with your variables and so on :)
Create a Windows batch file with these 2 lines:
python your-program.py
pause
Using atexit
, you can pause the program right when it exits. If an error/exception is the reason for the exit, it will pause after printing the stacktrace.
import atexit
# Python 2 should use `raw_input` instead of `input`
atexit.register(input, 'Press Enter to continue...')
In my program, I put the call to atexit.register
in the except
clause, so that it will only pause if something went wrong.
if __name__ == "__main__":
try:
something_that_may_fail()
except:
# Register the pause.
import atexit
atexit.register(input, 'Press Enter to continue...')
raise # Reraise the exception.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With