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 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.
_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.
In Python 3 use input(): input("Press Enter to continue...") In Python 2 use raw_input(): raw_input("Press Enter to continue...")
An escape character is a backslash \ followed by the character you want to insert.
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With