我如何让我的python脚本等待,直到用户按下任何键?
当前回答
在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++运行时库(msvcrt)中的一些函数:
import msvcrt as m
def wait():
m.getch()
这应该等待一个按键。
注:
在python3中,raw_input()不存在。 在Python 2中,input(prompt)等价于eval(raw_input(prompt))。
其他回答
在Python 3中,使用input():
input("Press Enter to continue...")
在Python 2中,使用raw_input():
raw_input("Press Enter to continue...")
如果您想等待输入(这样用户敲击键盘不会导致一些意想不到的事情发生),请使用
sys.stdin.readline()
我不知道有什么平台独立的方法,但是在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("Press Enter to continue...")
将在使用Python 2时导致以下错误:
SyntaxError:解析时预期的EOF。
让代码在Python 2和Python 3上都能工作的简单修复是使用:
try:
input("Press enter to continue")
except SyntaxError:
pass
在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++运行时库(msvcrt)中的一些函数:
import msvcrt as m
def wait():
m.getch()
这应该等待一个按键。
注:
在python3中,raw_input()不存在。 在Python 2中,input(prompt)等价于eval(raw_input(prompt))。