我该如何让我的Python脚本等待用户按下任意键?
在Python 3中,使用input()
函数:
input("Press Enter to continue...")
在 Python 2 中,使用 raw_input()
:
raw_input("Press Enter to continue...")
这只等待用户按下回车键。
在Windows/DOS上,可能需要使用msvcrt
。 msvcrt
模块为您提供了访问Microsoft Visual C/C++运行时库(MSVCRT)中多个函数的方法:
import msvcrt as m
def wait():
m.getch()
这应该等待按键操作。
注:
在 Python 3 中,raw_input()
不再存在。
在 Python 2 中,input(prompt)
等同于 eval(raw_input(prompt))
。
input()
:input("Press Enter to continue...")
在Python 2中,请使用raw_input()
:
raw_input("Press Enter to continue...")
enter
键时,该怎么办? - noio在我的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)
如果您可以接受依赖于系统命令,您可以使用:
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()
已经验证在Windows、Linux和Mac OS X上可以与Python 2和3一起使用。
system
的返回值,然后调用sys.exit(0)
。 - James Taylor简单使用
input("Press Enter to continue...")
在使用Python 2时,会导致以下错误:
SyntaxError: 在解析时预期文件末尾(EOF)。
让代码可以同时在Python 2和Python 3上工作的简单修复方法是使用:
try:
input("Press enter to continue")
except SyntaxError:
pass
input
函数,而应该使用raw_input
函数。在Python 2中,input
等价于eval(raw_input())
。 - Blorgbeard跨平台,Python 2/3 代码:
# import sys, os
def wait_key():
''' Wait for a key press on the console and return it. '''
result = None
if os.name == 'nt':
import msvcrt
result = msvcrt.getwch()
else:
import termios
fd = sys.stdin.fileno()
oldterm = termios.tcgetattr(fd)
newattr = termios.tcgetattr(fd)
newattr[3] = newattr[3] & ~termios.ICANON & ~termios.ECHO
termios.tcsetattr(fd, termios.TCSANOW, newattr)
try:
result = sys.stdin.read(1)
except IOError:
pass
finally:
termios.tcsetattr(fd, termios.TCSAFLUSH, oldterm)
return result
我移除了fctl/non-blocking的内容,因为它会导致IOError,并且我不需要它。我使用这段代码是因为我想要它阻塞。
附加说明:
我在PyPI上实现了这个包,其中包含很多其他好东西,叫做console:
>>> from console.utils import wait_key
>>> wait_key()
'h'
getwch()
代替。#15 - Gringo SuavePython 手册中提供了以下内容:
import termios, fcntl, sys, os
fd = sys.stdin.fileno()
oldterm = termios.tcgetattr(fd)
newattr = termios.tcgetattr(fd)
newattr[3] = newattr[3] & ~termios.ICANON & ~termios.ECHO
termios.tcsetattr(fd, termios.TCSANOW, newattr)
oldflags = fcntl.fcntl(fd, fcntl.F_GETFL)
fcntl.fcntl(fd, fcntl.F_SETFL, oldflags | os.O_NONBLOCK)
try:
while 1:
try:
c = sys.stdin.read(1)
print "Got character", repr(c)
except IOError: pass
finally:
termios.tcsetattr(fd, termios.TCSAFLUSH, oldterm)
fcntl.fcntl(fd, fcntl.F_SETFL, oldflags)
这可以被应用到你的使用场景中。
if c: print(f"Got character {repr(c)}")
。目前为止,Python 3 FAQ上还没有相关内容。 - PeterK我不知道有没有跨平台的方法可以做到,但在Windows下,如果你使用msvcrt模块,你可以使用它的getch
函数:
import msvcrt
c = msvcrt.getch()
print 'you entered', c
mscvcrt还包括非阻塞的kbhit()
函数,可用于检查是否按下键,而无需等待(不确定是否有相应的curses函数)。 在UNIX下,有curses包,但不确定是否可以在不将其用于所有屏幕输出的情况下使用它。 这段代码在UNIX下运行:
import curses
stdscr = curses.initscr()
c = stdscr.getch()
print 'you entered', chr(c)
curses.endwin()
请注意,curses.getch()
返回所按键的序号,因此为了使其输出与原来相同,我必须对其进行类型转换。
input
does not continue if any key is pressed, only if enter is pressed. - ctrl-alt-delor