Python ожидание нажатия кнопки

Как заставить Python ждать нажатой клавиши

В Python 2 вы должны использовать raw_input() , поскольку input(prompt) эквивалентен eval(raw_input(prompt)) :

raw_input("Press Enter to continue. ") 

Это только ждет, пока пользователь нажмет ввод, поэтому вы можете использовать msvcrt ((только для Windows/DOS). Модуль msvcrt предоставляет вам доступ к ряду функций в Microsoft Visual C/C++ Runtime Library (MSVCRT) ):

import msvcrt as m def wait(): m.getch() 

Я получаю эту ошибку при попытке сделать это в Python 2.7: «SyntaxError: неожиданный EOF при синтаксическом анализе»

@Solarsaturn9 Solarsaturn9 и все большее и большее количество не делают. Таким образом, этот ответ не работал для меня и многих других, которые приходят сюда.

@richard с использованием input () должен работать и на других платформах. Смешно ставить точки за предоставление альтернативного решения только для Windows, когда первое решение является мультиплатформенным.

@Solarsaturn9 Solarsaturn9 прочитайте вопрос и ответьте снова: input не продолжается, если нажата какая-либо клавиша, только если нажата кнопка ввода.

@JonTirsen, потому что в Python 2.7 есть функция input, которая оценивает введенную вами строку. Чтобы исправить, используйте raw_input

Этот ответ должен сказать: «Для Python 3 вы можете использовать:», а затем добавить «Для Python 2 вы можете использовать raw_input ()»

Использование шестерки для Py2 и Py3-совместимого кода: from six.moves import input; input(«Press Enter to continue. «)

Один из способов сделать это в Python 2 — использовать raw_input() :

raw_input("Press Enter to continue. ") 

В python3 это просто input()

Использование шестерки для Py2 и Py3-совместимого кода: from six.moves import input; input(«Press Enter to continue. «)

На моем компьютере с Linux я использую следующий код. Это похоже на код, который я видел в другом месте (например, в старых FAQ по Python), но этот код вращается в узком цикле, где этого кода нет, и есть много странных угловых случаев, которые код не учитывает код делает.

def read_single_keypress(): """Waits for a single keypress on stdin. This is a silly function to call if you need to do it a lot because it has to store stdin current setup, setup stdin for reading single keystrokes then read the single keystroke then revert stdin back after reading the keystroke. Returns a tuple of characters of the key that was pressed - on Linux, pressing keys like up arrow results in a sequence of characters. Returns ('\x03',) on KeyboardInterrupt which can happen when a signal gets handled. """ import termios, fcntl, sys, os fd = sys.stdin.fileno() # save old state flags_save = fcntl.fcntl(fd, fcntl.F_GETFL) attrs_save = termios.tcgetattr(fd) # make raw - the way to do this comes from the termios(3) man page. attrs = list(attrs_save) # copy the stored version to update # iflag attrs[0] &= ~(termios.IGNBRK | termios.BRKINT | termios.PARMRK | termios.ISTRIP | termios.INLCR | termios. IGNCR | termios.ICRNL | termios.IXON ) # oflag attrs[1] &= ~termios.OPOST # cflag attrs[2] &= ~(termios.CSIZE | termios. PARENB) attrs[2] |= termios.CS8 # lflag attrs[3] &= ~(termios.ECHONL | termios.ECHO | termios.ICANON | termios.ISIG | termios.IEXTEN) termios.tcsetattr(fd, termios.TCSANOW, attrs) # turn off non-blocking fcntl.fcntl(fd, fcntl.F_SETFL, flags_save & ~os.O_NONBLOCK) # read a single keystroke ret = [] try: ret.append(sys.stdin.read(1)) # returns a single character fcntl.fcntl(fd, fcntl.F_SETFL, flags_save | os.O_NONBLOCK) c = sys.stdin.read(1) # returns a single character while len(c) > 0: ret.append(c) c = sys.stdin.read(1) except KeyboardInterrupt: ret.append('\x03') finally: # restore old state termios.tcsetattr(fd, termios.TCSAFLUSH, attrs_save) fcntl.fcntl(fd, fcntl.F_SETFL, flags_save) return tuple(ret) 

Источник

Читайте также:  Узнать модули в питоне

Make Python Wait For a Pressed Key

In this article, we will discuss how to pause the execution of Python code until a given key is pressed. This concept can be useful to simply pause Python execution or impose conditions on the code implementation. There are three ways to do this:

  1. Using keyboard package
  2. Using msvcrt / getch package
  3. Using the inbuilt input function

Before discussing those methods, let us discuss a concept we need to understand first.

Prerequisite step

Since we will be reading the key pressed, it is vital that the code editor or IDE we are using to implement these concepts accepts input from the user. I will, therefore, suggest you run the code snippets shown in this article using Visual Studio Code, PowerShell/ Terminal, or JuPyter. If you are running on Sublime Text, install the SublimeRepl package on the editor before running the code (see stackoverflow.com).

Once you are sure that your Python can take input, we can now proceed to discuss the three methods.

Method 1: Using the keyboard package

This package allows us to read the key pressed and then impose our condition at that point. It is not an inbuilt function in Python but can be installed using pip, that is, run pip install keyboard on Windows PowerShell. Once installed, we can execute the following code to learn how this method works:

The above code will keep running until key “q” is pressed, that is when “q” is pressed Python prints “You pressed q” and then the loop is terminated with a “break” keyword.

Читайте также:  Все цвета фона html

As an alternative to the above method, we can use the following line of code (In this case, Python waits until the escape key is pressed).

The package also has a function called read_key() that reads the key pressed. You can read more cool things you can do with the keyboard package in its documentation.

In Linux and macOS, you need to have SUDO (Super User DO) privileges to use the keyboard package for executing python code and installing the package.

Method 2: Use msvcrt / getch package

This inbuilt Python package provides useful functions in Microsoft Visual C/C++ Runtime Library (hence the name msvcrt). This article will leverage its functionality of reading the key pressed to pause Python execution.

In the above code snippet, msvcrt.getch() fetches the code pressed in byte format, and therefore we need to use UTF-8 decoding to get it in string format. For example, b’\x0c’ becomes ♀, b’\x1b’ becomes ← (this is the escape key, by the way).

You can input different non-standard characters with the Ctrl key and a letter to see how it works.

The code function introduced in this code snippet is chr(). It returns a string character from an integer (the integer represents the Unicode code point of the string character). Character 27 in the Unicode is an escape character, and therefore pressing the escape key matches chr(27) in the code. Therefore, the while loop is terminated only when the escape key is pressed. It is necessary to use the chr() function only when dealing with problematic decoded characters like escape key; otherwise, when dealing with alphabets, for example, we won’t need chr().

Читайте также:  Vscode php launch json

The msvcrt package is only available on Windows OS. On Linux and macOS, the getch package can be used to get the same functionalities as msvcrt. You might need to install the getch package by running pip install getch on the terminal. Once installed, you can now use the code below instead

Источник

Ожидание нажатия клавиши в Python

При программировании на Python порой возникает необходимость приостановить выполнение программы до тех пор, пока пользователь не нажмёт какую-либо клавишу. Классическим примером может быть игра или приложение, где необходимо дождаться реакции пользователя, чтобы продолжить выполнение кода.

Существуют различные способы реализации этого функционала в Python. Однако, стоит отметить, что некоторые из них могут работать только в определенных операционных системах.

Использование модуля msvcrt (только для Windows)

В операционной системе Windows можно использовать модуль msvcrt . Этот модуль предоставляет доступ к различным полезным функциям и переменным, доступным в стандартной библиотеке Microsoft Visual C Runtime. Для ожидания нажатия клавиши в коде Python можно использовать функцию msvcrt.getch() .

import msvcrt print("Ожидание нажатия клавиши. ") msvcrt.getch() print("Клавиша нажата!")

Использование модуля keyboard

Универсальным решением и для Windows, и для Unix-подобных систем (Linux, MacOS) является использование стороннего модуля keyboard . Этот модуль позволяет управлять клавиатурой, не зависимо от операционной системы. Для ожидания нажатия клавиши можно использовать функцию keyboard.read_key() .

import keyboard print("Ожидание нажатия клавиши. ") keyboard.read_key() print("Клавиша нажата!")

Перед использованием модуля keyboard необходимо установить его. Это можно сделать с помощью команды pip install keyboard в командной строке.

Использование модуля getch

Еще одним универсальным решением является использование модуля getch . Этот модуль предоставляет единую функцию getch.getch() , которая читает один символ с клавиатуры, не требуя нажатия Enter.

import getch print("Ожидание нажатия клавиши. ") getch.getch() print("Клавиша нажата!")

Подобно модулю keyboard , модуль getch также не входит в стандартную библиотеку Python и перед использованием его необходимо установить с помощью команды pip install getch в командной строке.

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

Источник

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