Вопрос-Ответ

How do I wait for a pressed key?

Как мне дождаться нажатия клавиши?

Как мне заставить мой скрипт python ждать, пока пользователь нажмет любую клавишу?

Переведено автоматически
Ответ 1

В Python 3 используйте input():

input("Press Enter to continue...")

В Python 2 используйте raw_input():

raw_input("Press Enter to continue...")

Однако это только ожидает, пока пользователь нажмет enter.


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

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

Это должно дождаться нажатия клавиши.


Примечания:

В Python 3, raw_input() не существует.
В Python 2, input(prompt) эквивалентно eval(raw_input(prompt)).

Ответ 2

В Python 3 используйте input():

input("Press Enter to continue...")

В Python 2 используйте raw_input():

raw_input("Press Enter to continue...")
Ответ 3

В моем ящике Linux я использую следующий код. Это похоже на код, который я видел в другом месте (например, в старых часто задаваемых вопросах по 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's 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)
Ответ 4

Если вас устраивает зависимость от системных команд, вы можете использовать:

from __future__ import print_function
import os
import platform

if platform.system() == "Windows":
os.system("pause")
else:
os.system("/bin/bash -c 'read -s -n 1 -p \"Press any key to continue...\"'")
print()

Было проверено, что он работает с Python 2 и 3 в Windows, Linux и Mac OS X.

2023-12-31 17:58 python