我如何让我的python脚本等待,直到用户按下任何键?
当前回答
python手册提供了以下内容:
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)
它可以滚动到您的用例中。
其他回答
如果你想看看他们是否按了一个确切的键(比如“b”),可以这样做:
while True:
choice = raw_input("> ")
if choice == 'b' :
print "You win"
input("yay")
break
python手册提供了以下内容:
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)
它可以滚动到您的用例中。
如果您想等待输入(这样用户敲击键盘不会导致一些意想不到的事情发生),请使用
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()返回所按键的序号,以便使其具有与我强制转换时相同的输出。
如果你可以依赖于系统命令,你可以使用:
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一起工作。