How to Keep a Python Script Output Window Open

How to keep a Python script output window open?

You have a few options:

  1. 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.

  2. 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().

  3. 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.

How can I stop python.exe from closing immediately after I get an output?

You can't - globally, i.e. for every python program. And this is a good thing - Python is great for scripting (automating stuff), and scripts should be able to run without any user interaction at all.

However, you can always ask for input at the end of your program, effectively keeping the program alive until you press return. Use input("prompt: ") in Python 3 (or raw_input("promt: ") in Python 2). Or get used to running your programs from the command line (i.e. python mine.py), the program will exit but its output remains visible.

Keep Windows Console open after a Python Error

Make a batch file:

C:\Python26\python.exe %1
IF %ERRORLEVEL% NEQ 0 PAUSE

Use that as your file association instead of python.exe directly. This will only cause the PAUSE statement to execute if python.exe returns an error

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.



Related Topics



Leave a reply



Submit