227

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?

rohitmishra
  • 8,739
  • 7
  • 33
  • 34
  • 7
    A belated +1000. I'm using python as a teaching language for a friend who uses Windows, and I could not believe how much trouble it was (at least based on existing documentation) getting to where we could run a script and see the output. – Cascabel Jul 23 '11 at 18:08
  • 2
    just drag/drop your script into a cmd windows – JinSnow Feb 10 '17 at 12:23
  • You would think the output window should stay open by default. It does when running Python in Mac OS. Very frustrating – Fandango68 Nov 30 '17 at 06:45
  • 1
    I'm going to link another question [Keep Windows Console open after a Python Error](https://stackoverflow.com/questions/2843545/keep-windows-console-open-after-a-python-error) to this one (which I've posted an answer for debugging with drag & drop python scripts.) – akinuri May 16 '18 at 09:06
  • See the answer that @maurizio posted below - it's the only one that doesn't need you to change your python scripts. – roryhewitt Sep 06 '18 at 20:42

27 Answers27

189

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.

M.M
  • 138,810
  • 21
  • 208
  • 365
nosklo
  • 217,122
  • 57
  • 293
  • 297
  • 10
    +1 to item 3. I use Scite as my Python editor and it simply keeps the output in its own output window. This is really useful because you can potentially see the output of more than one run in a single window. – Joris Timmermans Jun 16 '09 at 12:14
  • I am able to see the output by running it from an already open terminal. But I need to give the complete script address in the python command? Can that be avoided? When I use the raw_input() method, it gives me NameError: name 'raw_input'is not defined. Can you suggest an editor which automatically pauses after execution? – rohitmishra Jun 16 '09 at 12:20
  • 1
    @movingahead: maybe you are using python 3? in python 3 it was renamed to input(). But I would use python 2.6 for now, since python 3 lacks important third party libraries that haven't been ported yet. (see other questions on python 2vs3). About editor, I don't use windows, notepad++ lets you configure the command. I use emacs which has a windows version, but I never used it. – nosklo Jun 16 '09 at 13:30
  • @nosklo thanks!! Yah I am using Python 3. Doing basic stuff now so shouldn't be much of an issue. I will try notepad++. Am currently trying out Pydev for Eclipse – rohitmishra Jun 16 '09 at 14:25
  • @movingahead I use Aptana studio. (pydev pre packaged). its really good. nothing to say. – v.oddou Jan 19 '15 at 03:20
  • 3
    I have an even better way: use `os`. I use the following code: `import os os.system("PAUSE")` for windows and `import os os.system('read -p ""')`. This seems like a cleaner way to do it. – IronManMark20 May 04 '15 at 23:15
  • Option 3 should be the first item in this list. – Jonny Feb 16 '17 at 16:58
  • @Jonny while I agree it is the best option, I think it is better to keep it as the last one in the post to help understanding the problem. – nosklo Apr 11 '17 at 17:26
  • Implementing option 3 works in NotePad++ for python 3 – DaveK Aug 28 '18 at 12:25
  • Any way of adapting method 1) without needing to physically open a new terminal? I'm looking for a solution which works with all windows shortcuts. – AnnanFay Jan 01 '21 at 21:54
65

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.

tzot
  • 92,761
  • 29
  • 141
  • 204
  • 3
    Fantastic answer. You should have got this. – Jagu Oct 26 '11 at 06:08
  • 1
    Just fyi for the python os.system command you would do os.system( "cmd /k " + myAppPath + " " + myFlagsString ) – Jay Dec 06 '11 at 08:01
  • 1
    `cmd /k` is Windows-only. I can't help with a Mac alternative, sorry. – tzot Mar 09 '12 at 17:20
  • Do you have to drag the script, including the Python command itself? Sorry can I have an example please? I am new, very new to Python under windows. – Fandango68 Nov 30 '17 at 06:51
  • 1
    This answer was the most straight forward and does exactly what I needed in a windows environment. Once the program executes the terminal window stays open. – CameronAtkinson Dec 16 '19 at 02:41
  • This also works for shortcuts to python build utilities, and is probably the most useful case. So you can change a desktop shortcut to python/pipenv/pyenv/etc so it stays open on an error. – AnnanFay Jan 01 '21 at 21:58
57

Start the script from an already open cmd window or at the end of the script add something like this, in Python 2:

 raw_input("Press enter to exit;")

Or, in Python 3:

input("Press enter to exit;")
Community
  • 1
  • 1
Anurag Uniyal
  • 85,954
  • 40
  • 175
  • 219
26

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()
Antonio
  • 19,451
  • 13
  • 99
  • 197
19

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

feinmann
  • 1,060
  • 1
  • 14
  • 20
  • This makes a great Windows batch file, if you change $(FULL_CURRENT_PATH) to a Windows path name. – Noumenon Jul 27 '15 at 13:27
  • I found it much easier to get the pluggin PyNPP and assign a shortcut to run it (don't forget to disable the previous F5 shortcut) – JinSnow Nov 24 '16 at 05:50
18

Create a Windows batch file with these 2 lines:

python your-program.py

pause
Gyrocode.com
  • 57,606
  • 14
  • 150
  • 185
maurizio
  • 181
  • 1
  • 2
  • 5
    Or `import os os.system("pause")` at the end of the `.py` file – Spikatrix May 25 '15 at 11:38
  • 9
    This is the only answer here that's even remotely correct. Answers that require corrupting _every single Python script you will ever run_ with `raw_input` or other garbage are simply wrong. Either type your command on the command line the way Python expects you to, or use the [batch language](https://en.wikipedia.org/wiki/List_of_DOS_commands#PAUSE) that has been provided with MS-DOS for _exactly this purpose_ since [August 1981](https://en.wikipedia.org/wiki/Timeline_of_DOS_operating_systems#8108). – Kevin J. Chase Jun 06 '16 at 16:22
  • 2
    even better, use `python %*` and set it as one of the "open with" programs so you can either right click a .py file to open a pausing window or I also put it in my Anaconda3 folder (in PATH) as py_pause.bat so now I can run `py_pause my-prog.py all my args` from the cmd line – brian May 24 '17 at 20:40
  • @Spikatrix Your comment merits to be an answer! This is more elegant than the most of others here. – Vovin May 05 '22 at 13:27
13

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.
leewz
  • 3,201
  • 1
  • 18
  • 38
9

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)
Brandon Aguilar
  • 389
  • 6
  • 14
7

On Python 3

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

Will do the trick.

DbxD
  • 540
  • 2
  • 15
  • 29
7

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}
Badro Niaimi
  • 959
  • 1
  • 14
  • 28
6

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.

Christian Specht
  • 35,843
  • 15
  • 128
  • 182
Matej
  • 932
  • 4
  • 14
  • 22
  • 1
    You may want to add ";C:\Python27" to the end of your Path environment variable. That way it can be shortened to 'cmd /k python -i "$(FULL_CURRENT_PATH)"' - Exactly what the answer above says plus the useful -i. – Enigma Dec 12 '12 at 23:34
3

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)

Mr Whybull
  • 31
  • 1
3

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"
Paul Stevens
  • 1,617
  • 1
  • 8
  • 4
2

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.

user3836103
  • 135
  • 1
  • 6
2

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)

roryhewitt
  • 4,097
  • 3
  • 27
  • 33
1

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)
Jackssn
  • 1,346
  • 1
  • 14
  • 16
1

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.

peter tom
  • 11
  • 1
1

The simplest way:

your_code()

while True:
   pass

When you open the window it doesn't close until you close the prompt.

Wolf
  • 17
  • 4
0
`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()`
0

Try this,

import sys

stat='idlelib' in sys.modules

if stat==False:
    input()

This will only stop console window, not the IDLE.

yourson
  • 88
  • 1
  • 4
  • 18
0

You can launch python with the -i option or set the environment variable PYTHONINSPECT=x. From the docs:

inspect interactively after running script; forces a prompt even if stdin does not appear to be a terminal; also PYTHONINSPECT=x

So when your script crashes or finishes, you'll get a python prompt and your window will not close.

ababak
  • 1,685
  • 1
  • 11
  • 23
0

Create a function like dontClose() or something with a while loop:

import time

def dontClose():
    n = 1
    while n > 0:
        n += 1
        time.sleep(n)
        

then run the function after your code. for e.g.:

print("Hello, World!")
dontClose()
-1
  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
demongolem
  • 9,474
  • 36
  • 90
  • 105
oldmcf
  • 11
  • 1
-2

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)

-2

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.

-3

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.

Kaycee
  • 123
  • 1
  • 1
  • 4
-3

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.

barshopen
  • 1,190
  • 2
  • 15
  • 28