18

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 an error. I want a code that closes your script without using an error.

Does anyone have an 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
Nitwit
  • 291
  • 3
  • 13
Joppe De Cuyper
  • 394
  • 1
  • 6
  • 17
  • 1
    `input =('Press Any Key To Exit')` Do you mean `input('Press Any Key To Exit')`? The first one will do nothing. Also, try using raw_input(). – Josiah Aug 09 '12 at 04:04
  • the first one will do nothing, but it should not throw any error.. it will just rebind the name input to that string – wim Aug 09 '12 at 04:05
  • @wim Agreed, that's why I assume he typed the question incorrectly and suggested trying `raw_input()`. – Josiah Aug 09 '12 at 04:06
  • so, i fixed the code above,deleted the =, im using python 2.7 btw – Joppe De Cuyper Aug 09 '12 at 04:09
  • http://stackoverflow.com/questions/10220943/present-blank-screen-wait-for-key-press-how – Alex W Aug 09 '12 at 04:13

10 Answers10

19

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

Community
  • 1
  • 1
vikki
  • 2,766
  • 1
  • 20
  • 26
15

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()
wim
  • 338,267
  • 99
  • 616
  • 750
4

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()
LISTERINE
  • 923
  • 1
  • 9
  • 14
3

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.

wim
  • 338,267
  • 99
  • 616
  • 750
Joe
  • 16,328
  • 12
  • 61
  • 75
2
a = input('Press a key to exit')
if a:
    exit(0)
Pullie
  • 2,685
  • 3
  • 25
  • 31
Nitwit
  • 291
  • 3
  • 13
1

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!'
Community
  • 1
  • 1
Matthew Adams
  • 9,426
  • 3
  • 27
  • 43
0

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.

  • 1
    Welcome to StackOverflow! You should post short snippets like this as a part of your answer. The editor provides the code block and inline code tools to support you. This will make your anwer easier for others to read. Read more about how to write a good answer in the [help center](http://stackoverflow.com/help/how-to-answer). – Michael Jaros Mar 08 '15 at 19:02
  • @DGxInfinitY from one Linux Mint fan to another.. I learned the hard way from what you tried to do. Linux Mint, and probably any Linux comes with a "system python", often both 2 and 3. It may be possible but you should not mess with it, upgrade it, downgrade it, install modules into it. Use 'virtualenv' with 'virtualenvwrapper', is convenient, keeps system Python clean. Otherwise one day, you might do something to the system Python and reboot and the gui and other stuff will be broken. – cardamom Dec 17 '18 at 14:43
0

in Windows:

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

In python 3:

  while True: 
        #runtime..
        answer = input("ENTER something to quit: ") 
        if answer: 
            break 
BARIS KURT
  • 477
  • 4
  • 15
  • This answer is similar to others already included in the post. Also, the question is tagged Python 2.7, so you might want to specify that your answer assumes a Python 3 environment – aaossa Apr 03 '22 at 19:10
0

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")
  • This does not provide an answer to the question. Once you have sufficient [reputation](https://stackoverflow.com/help/whats-reputation) you will be able to [comment on any post](https://stackoverflow.com/help/privileges/comment); instead, [provide answers that don't require clarification from the asker](https://meta.stackexchange.com/questions/214173/why-do-i-need-50-reputation-to-comment-what-can-i-do-instead). - [From Review](/review/late-answers/32614573) – Luis Alejandro Vargas Ramos Sep 06 '22 at 17:53