如何让python等待按下的键我希望我的脚本等到用户按任意键。我怎么做?
3 回答
GCT1015
TA贡献1827条经验 获得超4个赞
在Python 3中,不raw_input()存在。所以,只需使用:
input("Press Enter to continue...")在Python 2中,您应该使用raw_input(),input(prompt)相当于eval(raw_input(prompt)):
raw_input("Press Enter to continue...")这只等待用户按Enter键,因此您可能需要使用msvcrt((仅限Windows / DOS)msvcrt模块允许您访问Microsoft Visual C / C ++运行时库(MSVCRT)中的许多函数):
import msvcrt as mdef wait(): m.getch()
这应该等待按键。
胡子哥哥
TA贡献1825条经验 获得超6个赞
在Python 2中执行此操作的一种方法是使用raw_input():
raw_input("Press Enter to continue...")在python3中它只是 input()
大话西游666
TA贡献1817条经验 获得超14个赞
在我的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)添加回答
举报
0/150
提交
取消
