Python, Press Any Key To Exit - python

So, as the title says, I want a proper code to close my python script.
So far, I've used input('Press Any Key To Exit'), but what that does, is generate a error.
I would like a code that just closes your script without using a error.
Does anyone have a idea? Google gives me the input option, but I don't want that
It closes using this error:
Traceback (most recent call last):
File "C:/Python27/test", line 1, in <module>
input('Press Any Key To Exit')
File "<string>", line 0
^
SyntaxError: unexpected EOF while parsing

If you are on windows then the cmd pause command should work, although it reads 'press any key to continue'
import os
os.system('pause')
The linux alternative is read, a good description can be found here

This syntax error is caused by using input on Python 2, which will try to eval whatever is typed in at the terminal prompt. If you've pressed enter then Python will essentially try to eval an empty string, eval(""), which causes a SyntaxError instead of the usual NameError.
If you're happy for "any" key to be the enter key, then you can simply swap it out for raw_input instead:
raw_input("Press Enter to continue")
Note that on Python 3 raw_input was renamed to input.
For users finding this question in search, who really want to be able to press any key to exit a prompt and not be restricted to using enter, you may consider to use a 3rd-party library for a cross-platform solution. I recommend the helper library readchar which can be installed with pip install readchar. It works on Linux, macOS, and Windows and on either Python 2 or Python 3.
import readchar
print("Press Any Key To Exit")
k = readchar.readchar()

msvrct - built-in Python module solution (windows)
I would discourage platform specific functions in Python if you can avoid them, but you could use the built-in msvcrt module.
>>> from msvcrt import getch
>>>
>>>
... print("Press any key to continue...")
... _ = getch()
... exit()

A little late to the game, but I wrote a library a couple years ago to do exactly this. It exposes both a pause() function with a customizable message and the more general, cross-platform getch() function inspired by this answer.
Install with pip install py-getch, and use it like this:
from getch import pause
pause()
This prints 'Press any key to continue . . .' by default. Provide a custom message with:
pause('Press Any Key To Exit.')
For convenience, it also comes with a variant that calls sys.exit(status) in a single step:
pause_exit(0, 'Press Any Key To Exit.')
Check it out.

a = input('Press a key to exit')
if a:
exit(0)

Here's a way to end by pressing any key on *nix, without displaying the key and without pressing return. (Credit for the general method goes to Python read a single character from the user.) From poking around SO, it seems like you could use the msvcrt module to duplicate this functionality on Windows, but I don't have it installed anywhere to test. Over-commented to explain what's going on...
import sys, termios, tty
stdinFileDesc = sys.stdin.fileno() #store stdin's file descriptor
oldStdinTtyAttr = termios.tcgetattr(stdinFileDesc) #save stdin's tty attributes so I can reset it later
try:
print 'Press any key to exit...'
tty.setraw(stdinFileDesc) #set the input mode of stdin so that it gets added to char by char rather than line by line
sys.stdin.read(1) #read 1 byte from stdin (indicating that a key has been pressed)
finally:
termios.tcsetattr(stdinFileDesc, termios.TCSADRAIN, oldStdinTtyAttr) #reset stdin to its normal behavior
print 'Goodbye!'

Ok I am on Linux Mint 17.1 "Rebecca" and I seem to have figured it out, As you may know Linux Mint comes with Python installed, you cannot update it nor can you install another version on top of it. I've found out that the python that comes preinstalled in Linux Mint is version 2.7.6, so the following will for sure work on version 2.7.6. If you add raw_input('Press any key to exit') it will not display any error codes but it will tell you that the program exited with code 0. For example this is my first program. MyFirstProgram. Keep in mind it is my first program and I know that it sucks but it is a good example of how to use "Press any key to Exit"
BTW This is also my first post on this website so sorry if I formatted it wrong.

in Windows:
if msvcrt.kbhit():
if msvcrt.getch() == b'q':
exit()

In python 3:
while True:
#runtime..
answer = input("ENTER something to quit: ")
if answer:
break

You can use this code:
from os import system as console
console("#echo off&cls")
#Your main code code
print("Press Any Key To Exit")
console("pause>NUL&exit")

Related

Get user console input before user hitting enter

I have a quite simple problem.
I want to get some console input from a user (without an enter press at the end) and do something with it right away.
I quickly saw that the input() function from python would not work. I thought maybe you could write something like this:
sys.stdout.write("Input: ")
while True:
line = sys.stout.readline()
// Do something with the lines
But unfortunately it does not work because stdout is not readable. With stdin it does not work either because it waits for a enter press of the user.
Is it somehow possible to get lines without the user submit it?
You can get input from console interactively in byte format instead of getting a string with input command.
import sys
while True:
c = sys.stdin.read(1) # Read one byte
Here is what you might be looking for.
To get this working you will need to use pip install keyboard in the command line first.
import keyboard
while True:
key_pressed = keyboard.read_key()
print(f'You pressed {key_pressed}.')

How do I erase a residual character at prompt after exiting python program

I am writing Python menu programs, and are capturing key strikes (no ) and that's working OK. The problem is when I exit the program using sys.exit() the last keystrike ends up on the command line.
I'm using the 'keyboard' module which required pip install, but I'm open to suggestion on other ways to capture the key strike. I've tried using msvcrt.getch(), sys.stdout.flush(), sys.stdin.flush() before exiting, to no avail. In the code below, the character echoed to the command line is not necessarily upper case, depending on the caps lock.
Thanks in advance. This has to be a common problem, but I've spent a lot of time searching and so far nothing that works.
import keyboard
import sys
key = keyboard.read_key()
key = key.upper()
print('Key pressed: '+key)
sys.exit() # leaves residual character on the command line

readkey command in python

I want my Python program to stop and wait until any key is pressed, then to print the key that was just pressed.
It's like the Pascal's command key := readkey; writeln(key);.
I' ve tried yet to use the msvcrt module and the getch command but it didn' t work. I tried this:
import msvcrt
s = msvcrt.getch()
print (s)
And it didn' t wait I pressed a key, it immediately printed b'\xff' and it ended the program
I' m working with python 3.4
Do you know any way to help me ?
I found out that if I started my .py file from the command line (pythonw) the command msvcrt.getch() didn' t work but if I save my .py file and I launched it, the command msvcrt.getch() worked correctly !
Im not sure this will be usefull for anyone but the answer to this is
s = input()
This will store the input in the "s" variable.

Stop Windows from closing Python

This question may have been asked a couple of times but I cannot seem to find it.
Basically I am just learning Python and I am on Windows, this means I double click the .py file and open it. This works great until an error appears, at which point Python calls exit and the window closes.
One way, of course, to get around this is to use the cmd program in Windows and run the Python program from there, however, is there a way to fix it so that my application doesn't bail out and close as soon as it hits an error if I open it from Windows Explorer?
while(True):
try:
number = input('Enter a number: ')
if(is_int(number) is False):
print('Please actually enter a number')
if(number > 0):
answer = input('Oh Noes you really want that?')
if(answer == 'yes'):
sys.exit(0);
except KeyboardInterrupt:
sys.exit(0)
except Exception as e:
input('')
In order to keep your program intact, e.g. to not introduce unwanted catch-em-all exception handling (aka pokemon handling) there are at least three options:
Use any console terminal, e.g. built-in cmd or powershell or any third-party console apps out there.
Use any IDE: pycharm, IDLE (python windows installer by default sets it up) or whatever you have capable of running python code.
Use text editor plugins for running python code. At least notepad++ and sublime text are capable of doing so.
I would recommend starting with option 1 for starters, then slowly move to option 3 for small scripts and projects, and option two for larger ones.
I you put an input function at the bottom of your script then it will hang there until you hit enter or close the command prompt. If you call an exit function put it immediately before the exit function is called. Otherwise place it at the bottom of the script.
Also I assume you have defined is_int already in your script?
What would you think it should do?
Python is drawing the window you see, if python crashes, the windows is going away.
You can run it trough cmd, or within an IDE. (like IDLE, that has some problem though when it comes to GUI)
Otherwise, add something like this at the end of the file
try:
run()
except Exception as inst:
print type(inst), inst.args
#it prints the exception
print sys.exc_traceback.tb_lineno
#if you want the line number where the error occurred in the source code
raw_input()
inst is the exception instance, you can see the type and the list of arguments.
Then with the sys module you can also see the line where the error occurred in the code.
This way every error will be handled and displayed before closing
Is this the right way?
No. You should really be using ad IDE (like Eclipse with PyDev or PyCharm).
After #SeçkinSavaşçı's extremely useful comment at the start:
The most common way is to let it wait for an input, then ignore the input and terminate the script.
Which took me a second to understand I went in search of how to do this, so first I saw to stop the script and used:
while(True):
try:
# Application code here
except:
input('')
Which worked really well to catch all errors, which unlike in PHP (which I have become comfortable with unfortunately) are all exceptions.
So the next part was to to tell me what error had occured and how to fix it, I needed a backtrace. It just so happens that the Python docs gave me the answer right here: http://docs.python.org/2/library/traceback.html#traceback-examples in an easy to see example:
exc_type, exc_value, exc_traceback = sys.exc_info()
print(traceback.print_exception(exc_type, exc_value, exc_traceback, limit=2, file=sys.stdout));
Add that above the input('') and I had my perfect error handling showing me everything I needed.
Thanks all,
Try import time and time.sleep(). Also, I recommend you to use IDLE or Geany. I've been using them and they work out well.

Display previous input on keyup from user, in Python?

I have a simple Python program which uses a read-eval-print loop to read user input via raw_input and then print things to the screen. I would like to keep a history of previous inputs and cycle through them when the user presses keyup or keydown, similar to the Python interpreter or to the bash shell. How can I do this in Python?
Someone asked for sample code:
while True:
user_input = raw_input()
print user_input + " this many hats!!!"
I'd like to make it so a keyup puts the last line of input on the command line. The first answer given, use the readline module, is likely the best.
Try using the readline module. If your platform supports readline, simply importing the module should make its functionality available via the raw_input prompt.
For standard input function also works. No configuration needed. Just import readline.

Categories