msvcrt.getch()每次都会检测空间 [英] msvcrt.getch() detects space every time

查看:233
本文介绍了msvcrt.getch()每次都会检测空间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个简单的python代码,该代码应该可以检测到我的击键,但是由于某种原因在每次击键后都可以检测到空间.

Im writting a simple python code that should detect the my keystrokes but for some reason in detects space after everysingle keystroke.

代码:

import msvcrt

print("press 'escape' to quit...")
text=""
while 1:
    char = msvcrt.getch()
    print(ord(char))

样品运行:

Input: aaaaa

Output:
97
0
97
0
97
0
97
0
97
0

推荐答案

它没有检测到空间.空格是32,而不是0.

It's not detecting space. Space is 32, not 0.

发生的事情是,您正在使用宽字符终端,但将其读取为字节,因此您看到的是UTF-16-LE字节.在UTF-16-LE中,a是两个字节,970.如果您将它们看成是两个ASCII字符而不是一个UTF-16-LE字符,则将得到a,然后是\0.

What's happening is that you're using a wide-character terminal, but reading it as bytes, so you're seeing the UTF-16-LE bytes. In UTF-16-LE, an a is two bytes, 97 and 0. If you read those as if they were two ASCII characters instead of one UTF-16-LE character, you'll get a followed by \0.

请注意,您得到的实际上不是'a\0a\0a\0',而是b'a\0a\0a\0'.因此,您可以将它们缓冲到bytesbytearray中,并在其上使用decode('utf-16-le').但这违反了一次读取一个字符的目的.

Notice that what you get back isn't actually 'a\0a\0a\0', but b'a\0a\0a\0'. So you could buffer these up into a bytes or bytearray and use decode('utf-16-le') on it. But that defeats the purpose of reading one character at a time.

最简单的解决方法是使用 getwch 而不是getch.多数情况下,这将只是您要​​执行的操作-返回一个像'a'这样的单字符str值,而不是两个单独的单字节bytes值.

The simplest fix is to use getwch instead of getch. This will mostly just do what you want—return a single-character str value like 'a' rather than two separate single-byte bytes values.

星体字符(在U+FFFF上的所有字符)显示为两个单独的替代项而不是一个字符可能仍然存在一些问题,并且特殊键"仍将显示为Unicode U+0000U+00E0后面跟一个键码(或者,如果您使用的是较旧的Python,则可能是损坏的U+E0xx,其中的键码已嵌入字符中).否则,它将按您期望的方式工作.

There may still be some problems with astral characters (everything above U+FFFF) showing up as two separate surrogates instead of one single character, and "special keys" will still show up as a Unicode U+0000 or U+00E0 followed by a keycode (or, if you have an older Python, possibly as a broken U+E0xx with the keycode embedded in the character). But otherwise, it'll work the way you expected.

这篇关于msvcrt.getch()每次都会检测空间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆