[python] How to keep a Python script output window open?

I have just started with Python. When I execute a python script file on Windows, the output window appears but instantaneously goes away. I need it to stay there so I can analyze my output. How can I keep it open?

This question is related to python windows

The answer is


`import sys,traceback
sys.exc_info()[0]
traceback.format_exc()
print("Press Enter to exit ...")
input()`

simply write the above code after your actual code. for eg. am taking input from user and print on console hence my code will be look like this -->

`import sys,traceback
nam=input("enter your name:")
print("your name is:-{}".format(nam)) #here all my actual working is done
sys.exc_info()[0]
traceback.format_exc()
print("Press Enter to exit ...")
input()`

The simplest way:

import time

#Your code here
time.sleep(60)
#end of code (and console shut down)

this will leave the code up for 1 minute then close it.


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 ;)")

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.

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 :)


On Python 3

input('Press Enter to Exit...')

Will do the trick.


I had a similar problem. With Notepad++ I used to use the command : C:\Python27\python.exe "$(FULL_CURRENT_PATH)" which closed the cmd window immediately after the code terminated.
Now I am using cmd /k c:\Python27\python.exe "$(FULL_CURRENT_PATH)" which keeps the cmd window open.


Apart from input and raw_input, you could also use an infinite while loop, like this: while True: pass (Python 2.5+/3) or while 1: pass (all versions of Python 2/3). This might use computing power, though.

You could also run the program from the command line. Type python into the command line (Mac OS X Terminal) and it should say Python 3.?.? (Your Python version) It it does not show your Python version, or says python: command not found, look into changing PATH values (enviromentl values, listed above)/type C:\(Python folder\python.exe. If that is successful, type python or C:\(Python installation)\python.exe and the full directory of your program.


You can just write

input()

at the end of your code

therefore when you run you script it will wait for you to enter something

{ENTER for example}

To keep your window open in case of exception (yet, while printing the exception)

Python 2

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

Python 3

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

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.


A very belated answer, but I created a Windows Batch file called pythonbat.bat containing the following:

python.exe %1
@echo off
echo.
pause

and then specified pythonbat.bat as the default handler for .py files.

Now, when I double-click a .py file in File Explorer, it opens a new console window, runs the Python script and then pauses (remains open), until I press any key...

No changes required to any Python scripts.

I can still open a console window and specify python myscript.py if I want to...

(I just noticed @maurizio already posted this exact answer)


If you want to stay cmd-window open AND be in running-file directory this works at Windows 10:

cmd /k cd /d $(CURRENT_DIRECTORY) && python $(FULL_CURRENT_PATH)

  1. Go here and download and install Notepad++
  2. Go here and download and install Python 2.7 not 3.
  3. Start, Run Powershell. Enter the following. [Environment]::SetEnvironmentVariable("Path", "$env:Path;C:\Python27", "User")
  4. Close Powershell and reopen it.
  5. Make a directory for your programs. mkdir scripts
  6. Open that directory cd scripts
  7. In Notepad++, in a new file type: print "hello world"
  8. Save the file as hello.py
  9. Go back to powershell and make sure you are in the right directory by typing dir. You should see your file hello.py there.
  10. At the Powershell prompt type: python hello.py

You can open PowerShell and type "python". After Python has been imported, you can copy paste the source code from your favourite text-editor to run the code.

The window won't close.


I found the solution on my py3 enviroment at win10 is just run cmd or powershell as Administrator,and the output would stay at the same console window,any other type of user run python command would cause python to open a new console window.


If you want to run your script from a desktop shortcut, right click your python file and select Send to|Desktop (create shortcut). Then right click the shortcut and select Properties. On the Shortcut tab select the Target: text box and add cmd /k in front of the path and click OK. The shortcut should now run your script without closing and you don't need the input('Hit enter to close')

Note, if you have more than one version of python on your machine, add the name of the required python executable between cmd /k and the scipt path like this:

cmd /k python3 "C:\Users\<yourname>\Documents\your_scipt.py"

Try this,

import sys

stat='idlelib' in sys.modules

if stat==False:
    input()

This will only stop console window, not the IDLE.


On windows 10 insert at beggining this:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

Strange, but it work for me!(Together with input() at the end, of course)


In python 2 you can do it with: raw_input()

>>print("Hello World!")    
>>raw_input('Waiting a key...')

In python 3 you can do it with: input()

>>print("Hello world!")    
>>input('Waiting a key...')

Also, you can do it with the time.sleep(time)

>>import time
>>print("The program will close in 5 seconds")
>>time.sleep(5)

Create a Windows batch file with these 2 lines:

python your-program.py

pause

To just keep the window open I agree with Anurag and this is what I did to keep my windows open for short little calculation type programs.

This would just show a cursor with no text:

raw_input() 

This next example would give you a clear message that the program is done and not waiting on another input prompt within the program:

print('You have reached the end and the "raw_input()" function is keeping the window open') 
raw_input()

Note!
(1) In python 3, there is no raw_input(), just input().
(2) Use single quotes to indicate a string; otherwise if you type doubles around anything, such as "raw_input()", it will think it is a function, variable, etc, and not text.

In this next example, I use double quotes and it won't work because it thinks there is a break in the quotes between "the" and "function" even though when you read it, your own mind can make perfect sense of it:

print("You have reached the end and the "input()" function is keeping the window open")
input()

Hopefully this helps others who might be starting out and still haven't figured out how the computer thinks yet. It can take a while. :o)


A simple hack to keep the window open:

counter = 0

While (True):

    If (counter == 0):

        # Code goes here

    counter += 1

The counter is so the code won’t repeat itself.