windows机器上python的无缓冲字符输入



我想做什么

我正在尝试设计一个计时秒表。当你按"L"键时,一圈就完成了,当你按"S"键时,所有圈都完成了,计时按顺序显示。

而在c++中,我可以通过conio.h中的_getch()函数来做到这一点,这将非常容易。我想用python写这个程序,因为它会容易得多,而且用c++处理时间被证明是困难的。

我还是写了一个程序(这是立方体计时)在这个链接:立方体计时器

没有像_getch()这样的函数。这是一个问题,因为在一圈结束时,你不能按下一个键和一个回车键,因为这将花费时间,并激怒用户。

things I read

我读了关于诅咒库,但可惜它没有windows端口。

我尝试了一个程序,应该是根据网站工作。这是来自链接

链接获取配方

但是没有成功。

我尝试了什么:

  1. msvcrt.getch()
<>之前>>>导入MSVCRT>>> msvcrt.getch ()" xff"之前

我相信FF是255的十六进制等效物。

我不明白为什么会这样。

  1. readch() 如@martineau建议

    进口msvcrt

    def readch (echo = True):"在Windows上获得一个字符。"而msvcrt.kbhit(): #清除键盘缓冲区msvcrt.getch ()Ch = msvcrt.getch()而ch在'x00xe0': #箭头或功能键前缀?msvcrt.getch ()Ch = msvcrt.getch() #第二次调用返回实际的键代码如果回声:msvcrt.putch (ch)返回ch.decode ()

    a = []

    for I in range(10):a.append (readch ())

我得到的错误:

>>> 
Traceback (most recent call last):
  File "C:/Python25/1.py", line 30, in <module>
    a.append(readch())
  File "C:/Python25/1.py", line 25, in readch
    return ch.decode()
UnicodeDecodeError: 'ascii' codec can't decode byte 0xff in position 0: ordinal not in range(128)

我需要什么帮助

在windows机器上工作的函数,类似于_getch()或类似的函数。

机规格

Python IDLE 2.5.4或2.6或2.7

Windows XP SP3

这是我在Windows控制台中使用的,似乎可以工作。它有点类似于ActiveState配方,除了它只适用于Windows。它基于_getwch()msdn文档。

#### windows only ####
import msvcrt
def readch(echo=True):
    "Get a single character on Windows."
    while msvcrt.kbhit():  # clear out keyboard buffer
        msvcrt.getwch()
    ch = msvcrt.getwch()
    if ch in u'x00xe0':  # arrow or function key prefix?
        ch = msvcrt.getwch()  # second call returns the actual key code
    if echo:
        msvcrt.putwch(ch)
    return ch
def pause(prompt='Press any key to continue . . .'):
    if prompt:
        print prompt,
    readch(echo=False)

(更新以处理Unicode)。

如果您正在询问如何在没有输入的情况下读取输入,您可能正在寻找绑定我认为这需要一个更大的窗口。

lapEnded = bind_all("<KeyPress-l>", endLap)
stopRunning = bind_all("<KeyPress-s", noMoreRunning)

然后,定义函数endLapnoMoreRunning,它们执行各自的功能。根据您的Tkinter和/或Python版本,bind_all可能只是bind

您不能在IDLE中使用msvcrt库。在Windows命令行中试试你的代码

最新更新