How to do “hit any key” in python?

匿名 (未验证) 提交于 2019-12-03 02:26:02

问题:

How would I do a "hit any key" (or grab a menu option) in Python?

  • raw_input requires you hit return.
  • Windows msvcrt has getch() and getche().

Is there a portable way to do this using the standard libs?

回答1:

try:     # Win32     from msvcrt import getch except ImportError:     # UNIX     def getch():         import sys, tty, termios         fd = sys.stdin.fileno()         old = termios.tcgetattr(fd)         try:             tty.setraw(fd)             return sys.stdin.read(1)         finally:             termios.tcsetattr(fd, termios.TCSADRAIN, old) 


回答2:

try:   os.system('pause')  #windows, doesn't require enter except whatever_it_is:   os.system('read -p "Press any key to continue"') #linux 


回答3:

From the python docs:

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", `c`         except IOError: pass finally:     termios.tcsetattr(fd, termios.TCSAFLUSH, oldterm)     fcntl.fcntl(fd, fcntl.F_SETFL, oldflags) 

This only works for Unix variants though. I don't think there is a cross-platform way.



回答4:

A couple years ago I wrote a small library to do this in a cross-platform way (inspired directly by John Millikin's answer above). In addition to getch, it comes with a pause function that prints 'Press any key to continue . . .':

pause() 

You can provide a custom message too:

pause('Hit any key') 

If the next step is to exit, it also comes with a convenience function that calls sys.exit(status):

pause_exit(status=0, message='Hit any key') 

Install with pip install py-getch, or check it out here.



回答5:

on linux platform, I use os.system to call /sbin/getkey command, e.g.

continue_ = os.system('/sbin/getkey -m "Please any key within %d seconds to continue..." -c  10') if continue_:    ... else:    ... 

The benefit is it will show an countdown seconds to user, very interesting :)



易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!