如何在python中"点击任何键"?

Nic*_*ick 30 python

我如何在Python中"点击任何键"(或获取菜单选项)?

  • raw_input要求你回击.
  • Windows msvcrt有getch()和getche().

有没有一种可移植的方法来使用标准库?

Joh*_*kin 34

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)
Run Code Online (Sandbox Code Playgroud)


Dus*_*etz 9

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

  • 产生io同步的子过程简直没用.不要这样做,它会破坏非交互性能,没有充分的理由. (5认同)
  • +1 因为它是一个简单的解决方案,可能足以满足 90% 的情况。 (2认同)
  • 有没有搞错?当一个没有头脑的单行代码会做的时候,甚至浪费10分钟编写15行代码会更糟糕. (2认同)

Alv*_*Row 5

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)
Run Code Online (Sandbox Code Playgroud)

但是,这仅适用于Unix变体。我认为没有跨平台的方式。


Joe*_*Joe 5

几年前,我编写了一个小型库来以跨平台的方式执行此操作(直接受到上面 John Millikin 回答的启发)。此外getch,它还带有一个pause打印功能'Press any key to continue . . .'

pause()
Run Code Online (Sandbox Code Playgroud)

您也可以提供自定义消息:

pause('Hit any key')
Run Code Online (Sandbox Code Playgroud)

如果下一步是退出,它还附带了一个调用的便利函数sys.exit(status)

pause_exit(status=0, message='Hit any key')
Run Code Online (Sandbox Code Playgroud)

安装pip install py-getch,或在此处查看