Press any key to exit python

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 input('Press Any Key To Exit') File "", line 0 ^ SyntaxError: unexpected EOF while parsing 

Solution

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() 

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Источник

Python, Press Any Key To Exit

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() 

Solution 2

If you are on windows then the cmd pause command should work, although it reads ‘press any key to continue’

Читайте также:  Обход бинарного дерева php

The linux alternative is read , a good description can be found here

Solution 3

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 junk = getch() # Assign to a variable just to suppress output. Blocks until key press. 

Solution 4

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.') 

Solution 5

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

Источник

Python, нажмите любую клавишу для выхода

Итак, как говорится в заголовке, я хочу, чтобы правильный код закрывал мой python script. До сих пор я использовал input(‘Press Any Key To Exit’) , но то, что это делает, генерирует ошибку. Мне нужен код, который просто закрывает ваш script без использования ошибки. Есть ли у кого-нибудь идеи? Google дает мне возможность ввода, но я не хочу, чтобы Он закрывается с использованием этой ошибки:

Traceback (most recent call last): File "C:/Python27/test", line 1, in input('Press Any Key To Exit') File "", line 0 ^ SyntaxError: unexpected EOF while parsing 

input =(‘Press Any Key To Exit’) Вы имеете в виду input(‘Press Any Key To Exit’) ? Первый ничего не сделает. Также попробуйте использовать raw_input ().

первый ничего не будет делать, но он не должен выдавать никакой ошибки .. он просто перепривязывает ввод имени к этой строке

@wim Согласен, поэтому я предполагаю, что он неправильно набрал вопрос и предложил попробовать raw_input() .

8 ответов

Вы пробовали raw_input() ? Возможно, вы получаете синтаксическую ошибку, используя input() на python 2.x, которая будет пытаться eval получить то, что получает.

Да, это исправило это, но я видел, что кто-то ответил, что это не доступно в 3.0, так что, если я обновлюсь, я снова застрял?

@JoppeDnbCuyper: raw_input переименовывается в input в Python 3.0, поэтому, если вы обновляетесь, вам просто нужно изменить каждый экземпляр raw_input на input

Если вы находитесь в окнах, то команда cmd pause должна работать, хотя она читает «нажмите любую клавишу, чтобы продолжить»

Альтернатива linux read , хорошее описание можно найти здесь

Немного опоздал к игре, но пару лет назад я написал библиотеку, чтобы сделать именно это. Он предоставляет как функцию pause() с настраиваемым сообщением, так и более общую кроссплатформенную getch() вдохновленную этим ответом.

Установите с помощью pip install py-getch и используйте его так:

from getch import pause pause() 

Это печатает ‘Press any key to continue. ‘ ‘Press any key to continue. ‘ по умолчанию. Предоставьте пользовательское сообщение с:

pause('Press Any Key To Exit.') 

Для удобства он также поставляется с вариантом, который вызывает sys.exit(status) за один шаг:

pause_exit(0, 'Press Any Key To Exit.') 

Я бы отказался от функций платформы на python, если вы можете их избежать, но вы можете использовать встроенный модуль msvcrt .

from msvcrt import getch junk = getch() # Assign to a variable just to suppress output. Blocks until key press. 
if msvcrt.kbhit(): if msvcrt.getch() == b'q': exit() 

Хорошо, я на Linux Mint 17.1 «Ребекка», и я, похоже, понял это. Как вы знаете, Linux Mint поставляется с установленным Python, вы не можете его обновить и не можете установить другую версию поверх нее. Я узнал, что питон, который поставляется с предустановленной в Linux Mint версией 2.7.6, так что наверняка работа над версией 2.7.6. Если вы добавите raw_input(‘Press any key to exit’) , он не отобразит никаких кодов ошибок, но он скажет вам, что программа вышла с кодом 0. Например, это моя первая программа. MyFirstProgram. Имейте в виду, что это моя первая программа, и я знаю, что это отстой, но это хороший пример того, как использовать «Нажмите любую клавишу для выхода», BTW Это также мой первый пост на этом сайте, так что извините, если я отформатировал его неправильно.

Читайте также:  Css selectors tag with class

Добро пожаловать в StackOverflow! Вы должны опубликовать короткие фрагменты, как это, как часть вашего ответа. Редактор предоставляет блок кода и встроенные инструменты кода для поддержки вас. Это облегчит чтение других людей. Узнайте больше о том, как написать хороший ответ в справочном центре .

@DGxInfinitY от одного поклонника Linux Mint к другому .. Я усвоил трудный путь из того, что ты пытался сделать. Linux Mint и, возможно, любой Linux поставляется с «системным питоном», часто и 2, и 3. Это может быть возможно, но вам не следует связываться с ним, обновлять его, понижать его версию, устанавливать в него модули. Использовать «virtualenv» с «virtualenvwrapper» удобно, поддерживает чистоту системы Python. Иначе однажды вы можете что-то сделать с системным Python и перезагрузиться, и графический интерфейс и другие вещи будут повреждены.

Здесь можно закончить, нажав любую клавишу на * nix, без отображения клавиши и без нажатия возврата. (Кредит за общий метод переходит на Python читает один символ от пользователя.) Из-за того, что вы можете использовать модуль msvcrt для дублирования эта функциональность в Windows, но у меня ее нет нигде для тестирования. Прокомментировал, чтобы объяснить, что происходит.

import sys, termios, tty stdinFileDesc = sys.stdin.fileno() #store stdin file descriptor oldStdinTtyAttr = termios.tcgetattr(stdinFileDesc) #save stdin 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!' 

Источник

Achieve python version of the press any key to continue and exit

One day, some students in the group asked, «under python, I have to enter input or raw_input to get the input value. Then how to achieve any key exit and pause functions?» I did not think much at that time, because the contact time of python was not long, mainly under Linux.

Читайте также:  Html url file path

To do this, all you need to do is pause the program, wait for and capture a user’s keyboard input, and then continue. Python has built-in libraries to help us do this, but make a distinction between Windows and Linux.

Of course, Windows is a little simpler. If you install python, Windows has a module called msvcrt, import msvcrt, and then msvcrt.getch ().

 #coding=utf-8 raw_input(unicode(' Press enter to exit . ','utf-8').encode('gbk')) 

2. Press any key to continue.

The next step is to press any key to exit the python version under Linux.

When I was just beginning to learn Python, I always wanted to achieve a program to press any key to continue/exit (under the.bat poison), but I couldn’t write it. When I recently learned Unix C, I found that it could be realized through termios.h library.

 #!/usr/bin/env python # -*- coding:utf-8 -*- import os import sys import termios def press_any_key_exit(msg): # Gets the descriptor for standard input fd = sys.stdin.fileno() # Get standard input ( terminal ) The setting of the old_ttyinfo = termios.tcgetattr(fd) # Configure the terminal new_ttyinfo = old_ttyinfo[:] # Use non-canonical patterns ( The index 3 is c_lflag That's the local mode ) new_ttyinfo[3] &= ~termios.ICANON # Close the echo ( The input will not be displayed ) new_ttyinfo[3] &= ~termios.ECHO # Output information sys.stdout.write(msg) sys.stdout.flush() # Enable Settings termios.tcsetattr(fd, termios.TCSANOW, new_ttyinfo) # Read from terminal os.read(fd, 7) # Restore terminal setting termios.tcsetattr(fd, termios.TCSANOW, old_ttyinfo) if __name__ == "__main__": press_any_key_exit(" Press any key to continue . ") press_any_key_exit(" Press any key to exit . ") 

Other information about termios can be found in the Linux manual:

In addition, there are 3 modes of *nix terminal (excerpted) < Unix-Linux programming practice tutorial >)

Specification model, also known as cooked mode, is a common pattern of the user. The driver input of characters stored in buffer, and only when receives the enter key to send these buffer character to the program. Data buffer so drivers can achieve the most basic editing features, was assigned to these functions of certain key setting in the driver, you can through the command to invoke tcsetattr stty or system changes

When buffering and editing functions are turned off, the connection is made into non-canonical mode. The terminal processor still performs specific character processing, such as the conversion between Ctrl-C and newline characters, but the edit key will not be meaningful, so the corresponding input is treated as normal data entry and the program needs to implement its own editing function

When all processing is turned off, the driver passes the input directly to the program and the connection is called raw mode.

Источник

Оцените статью