我正在尝试捕获我的击键,并将它们返回给我。当我运行代码时,我希望得到代码按该顺序运行时按下的所有键的信息。我在那里没有问题,一切都很好。但是然后在代码运行后,它返回'-Bash:( myinput ):命令未找到
from __future__ import print_function
import keyboard
keys = []
def keys_in():
try:
while True:
recorded = keyboard.read_key(suppress=True)
keys.append(recorded)
if recorded == 'enter':
print(sorted(set(keys),key=keys.index))
break
keys.append(recorded)
except KeyboardInterrupt:
print('done')
quit()
keys_in()
当我放入1234时,我会得到[['1','2','3','4','enter']
$ 1234 -bash:1234:找不到命令 而且我不确定为什么要尝试运行我的输入后记。帮助吗?
答案 0 :(得分:0)
import keyboard
s = set()
def keys_in():
recorded = keyboard.read_key(suppress=True)
while recorded != "enter":
s.add(recorded)
print(list(s))
keys_in()
尝试一下。集已经排序。您不需要添加。这样做吗?
答案 1 :(得分:0)
我对keyboard
模块不熟悉,但是看起来,尽管确实确实将输入传递给python程序,但是这样做的方式是,当python程序退出时,shell会获得输入,就像在命令行中输入的一样。这是两个选项(不需要安装键盘模块):
使用sys.stdin.read
from __future__ import print_function
import sys
keys = []
def keys_in():
try:
while True:
recorded = sys.stdin.read(1)
keys.append(recorded)
if recorded == '\n':
print(sorted(set(keys),key=keys.index))
break
keys.append(recorded)
except KeyboardInterrupt:
print('done')
quit()
keys_in()
使用“输入”
from __future__ import print_function
import sys
keys = []
def keys_in():
try:
input_string = input('')
for recorded in input_string:
keys.append(recorded)
except KeyboardInterrupt:
print('done')
quit()
print(sorted(set(keys),key=keys.index))
keys_in()