Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python, Press Any Key To Exit

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
like image 214
Joppe De Cuyper Avatar asked Aug 09 '12 04:08

Joppe De Cuyper


People also ask

How do you press a key to exit in Python?

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.

Is there any exit function in Python?

_exit() method in Python is used to exit the process with specified status without calling cleanup handlers, flushing stdio buffers, etc. Note: This method is normally used in the child process after os.

How do you add a press any key to continue in Python?

In Python 3 use input(): input("Press Enter to continue...") In Python 2 use raw_input(): raw_input("Press Enter to continue...")

What is the Escape key called in Python?

An escape character is a backslash \ followed by the character you want to insert.


2 Answers

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

like image 183
vikki Avatar answered Sep 17 '22 14:09

vikki


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()
like image 29
wim Avatar answered Sep 16 '22 14:09

wim