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?
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 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;")
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()
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.
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)
On Python 3
input('Press Enter to Exit...')
Will do the trick.
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}
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.
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)
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"
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.
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)
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.
The simplest way:
your_code()
while True:
pass
When you open the window it doesn't close until you close the prompt.
`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()`
Try this,
import sys
stat='idlelib' in sys.modules
if stat==False:
input()
This will only stop console window, not the IDLE.
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.
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()
Go here and download and install Notepad++
Go here and download and install Python 2.7 not 3.
Start, Run Powershell. Enter the following. [Environment]::SetEnvironmentVariable("Path", "$env:Path;C:\Python27", "User")
Close Powershell and reopen it.
Make a directory for your programs. mkdir scripts
Open that directory cd scripts
In Notepad++, in a new file type: print "hello world"
Save the file as hello.py
Go back to powershell and make sure you are in the right directory by typing dir. You should see your file hello.py there.
At the Powershell prompt type: python hello.py
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)
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.
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.
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.
Related
This code,
https://i.stack.imgur.com/E39QL.png
It opens the shell but as I fill the input fields, It closes without showing the output after creating its exe file.
main.py file,
https://i.stack.imgur.com/fKKTq.png
What can I do so that the shell remains visible after the code is completed?
The answer of a * b is shown so quickly that I can't even see the output and the shell closes.
Your problem is that the Python code exit with code 0 correctly and, consequently, the shell closes.
A solution could be adding a "press any key to exit" command at the end of your code. To do that you can use readchar as below. You can put it at the end of your code so when you click something, the shell closes. You also need to isntall it via pip install readchar
import readchar
print("Press Any Key To Exit")
k = readchar.readchar()
I'm creating an executable from my Python script now, and when something fails in the script (for example, a file is not present), I quit the script with sys.exit('*Enter reason here*'). This works excellent in the terminal view, because the output is still visible in the window. However, when I build an executable, the window is closed immediately, and the reason why the scripts ends, is not readable.
Is there an option to keep the command window open (preferably in PyInstaller)?
I found an option:
Because sys.exit()raises the error SystemExit it can be catch in a try-except statement. Even the text within sys.exit() can be catched! Because there is only one function that is called (main_function), it is a short and comprehensible option:
if __name__ == '__main__':
try:
main_function()
except SystemExit as e:
print 'Error!', e
print 'Press enter to exit (and fix the problem)'
raw_input()
I'm working with Windows :
import os
import http.client as h
co = h.HTTPSConnection("www.google.com")
co.request("GET","/")
res = co.getresponse()
print(res.status,res.reason)
os.system("pause")
When I open the command line, all work perfectly : "200 OK"
But when I copy this in a file and save it, I have an error and the programm stop.
I found a "solution", when I run my app, the folder "__pycache__" containing "http.cpython-34" is created.
And I have to open the "http.cpython-34" file to see "200 OK"
Is there another way to run correctly my programm without opening the "http.cpython-34" file ?
EDIT : I found the solution. My file was called http.py. But when I rename it, it work perfectly :)
I don't think os.system("pause") is what you want to use here. That will try to launch a subprocess with the command pause, which will not actually pause the running Python program. Generally if you want to pause and wait for a keypress or something you can use raw_input() to pause and wait for user input in Python 2.7 or input() in Python 3.
I'm using PythonWin. If in the IDE I click Run, then any input() commands will pop up as a windows message box. But in the console they are printed console commands.
I tried using msvcrt.getch() in PythonWin, and it returns the character \xFF every time.
I would like to have my program use msvcrt.getch() if it's in the console, and input() if it's in PythonWin. So, how can my program tell which one it's running in?
You can check if you are in a regular shell (python.exe) or a custom one (IPython, PythonWin, DreamPie...) by using os.isatty:
import os
import sys
import io
try:
if os.isatty(sys.stdin.fileno()):
print "msvcrt.getch() will work."
else:
print "msvcrt.getch() will fail."
except (AttributeError, io.UnsupportedOperation):
print "msvcrt.getch() will fail."
I was able to figure out a solution by stepping into the source code of input() when running through PythonWin. I am posting here so that others who run across this issue will have a solution.
"pywin.framework.startup" in sys.modules is True when running in PythonWin, but False when running in the console.
So my code looks like this:
if "pywin.framework.startup" in sys.modules:
move = raw_input(promptstr)
else:
print(promptstr)
move = msvcrt.getch()
I am running command-line Python scripts from the Windows taskbar by having a shortcut pointing to the Python interpreter with the actual script as a parameter.
After the script has been processed, the interpreter terminates and the output window is closed which makes it impossible to read script output.
What is the most straightforward way to keep the interpreter window open until any key is pressed?
In batch files, one can end the script with pause. The closest thing to this I found in python is raw_input() which is sub-optimal because it requires pressing the return key (instead of any key).
One way is to leave a raw_input() at the end so the script waits for you to press Enter before it terminates.
Try os.system("pause") — I used it and it worked for me.
Make sure to include import os at the top of your script.
There's no need to wait for input before closing, just change your command like so:
cmd /K python <script>
The /K switch will execute the command that follows, but leave the command interpreter window open, in contrast to /C, which executes and then closes.
The best option: os.system('pause') <-- this will actually display a message saying 'press any key to continue' whereas adding just raw_input('') will print no message, just the cursor will be available.
not related to answer:
os.system("some cmd command") is a really great command as the command can execute any batch file/cmd commands.
One way is to leave a raw_input() at the end so the script waits for you to press enter before it terminates.
The advantage of using raw_input() instead of msvcrt.* stuff is that the former is a part of standard Python (i.e. absolutely cross-platform). This also means that the script window will be alive after double-clicking on the script file icon, without the need to do
cmd /K python <script>
On Windows you can use the msvcrt module.
msvcrt.kbhit()
Return True if a keypress is waiting to be read.
msvcrt.getch()
Read a keypress and return the resulting character as a byte string. Nothing is echoed to the console. This call will block if a keypress is not already available, but will not wait for Enter to be pressed. If the pressed key was a special function key, this will return '\000' or '\xe0'; the next call will return the keycode. The Control-C keypress cannot be read with this function.
If you want it to also work on Unix-like systems you can try this solution using the termios and fcntl modules.
As to the "problem" of what key to press to close it, I (and thousands of others, I'm sure) simply use input("Press Enter to close").
There's a simple way to do this, you can use keyboard module's wait function. For example, you can do:
import keyboard
print("things before the pause")
keyboard.wait("esc") # esc is just an example, you can obviously put every key you want
print("things after the pause")
Getting python to read a single character from the terminal in an unbuffered manner is a little bit tricky, but here's a recipe that'll do it:
Recipe 134892: getch()-like unbuffered character reading from stdin on both Windows and Unix (Python)
On Windows 10 insert at beggining this:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
Strange, but it works for me! (Together with input() at the end, of course)
An external WConio module can help here: http://newcenturycomputers.net/projects/wconio.html
import WConio
WConio.getch()
import pdb
pdb.debug()
This is used to debug the script. Should be useful to break also.
If you type
input("")
It will wait for them to press any button then it will continue. Also you can put text between the quotes.