【发布时间】:2020-03-28 01:58:23
【问题描述】:
我在 Windows 7 系统上使用 Python 3.6.4(我有其他系统,如 Win 10 和 Android,但这是我的起点)。
INKEY$,对于那些不熟悉 BASIC(几乎任何风格)的人来说,是一个检查键盘缓冲区的函数,如果没有数据,则以字符串或空/空值 ("") 的形式返回该数据,并清除缓冲区。返回字符串的长度取决于缓冲区中的数据,通常是单次击键时的 0、1 或 2(在过去,快速打字员可以在两次检查之间填满小缓冲区)。 Enter 键不需要(除非您正在寻找)或已处理,并且程序不会暂停,除非被编程这样做。
暂停:
a$=""
while a$=""
a$=inkey$
wend
流量中断器:
a=0
while a < 1000
a=a+1
print a
a$=inkey$
if a$<>"" then exit while
wend
快速解析器:
a$=inkey$
if a$<>"" then
rem process input
rem like arrow keys/a w s z for directional movement
rem useful for games and custom editors
end if
我想知道 Python 是否有一个与 INKEY$ 函数等效的简单跨平台函数(即不是 10 多行代码,除非在可导入模块/类中)?另外,我不想导入游戏模块,只想要一个等效的 INKEY$ 函数(简单、直接、小)。
import inkey
a = inkey.inkey()
更新#1: 在我安装了 readchar 模块并更正了 Python 报告的错误之后(stdout.write(a) 需要是 stdout.write(str(a)),因为变量 'a' 似乎是作为 readchar() 的字节字符串返回的函数)当使用下面 Stratton 先生列出的代码时,如果有任何按键,我只会得到连续的 b'\xff' 流和控制台回显字符。
剥离它以仅使用该功能也无济于事:
from readchar import readchar
from sys import stdout
import os
#I like clear screens, and I can not lie
os.system('cls') # For Windows
#os.system('clear') # For Linux/OS X
def inkey():
"INKEY$ function"
return readchar()
#let the processing hit the floor, elsewhere
b=0
step = 1
while b < 1000:
b = b + step
print(b)
#convert bytes to integers
a = int.from_bytes(inkey(), "big")
#remember I keep getting b'\xff' (255) when buffer is empty
if chr(a) == "a":
step = step - 1
a = 255 #don't stop
if chr(a) == "l":
step = step + 1
a = 255 #don't stop
if a != 255:
break
它应该从 0 到 999 计数 b,几乎在任何按键上都停止,'a' 减少步骤,'l' 增加它。相反,它会根据时间在 b 的值之前或之后打印按键,并一直持续到 b = 1000。我所做的一切都没有改变。
虽然 Pauser 函数可以用 input() (i = input("Press Enter key to continue")) 替换,但其他两个变体似乎无法轻易更改。
【问题讨论】:
标签: python keyboard buffer basic