【发布时间】:2022-01-20 08:31:19
【问题描述】:
我正在开发一个程序,我需要用户输入进行选择,而不是专注于控制台窗口。我想使用的方法是在小键盘上使用键盘输入。我找到了这个库Python keyboard lib 来实现这一点。 我这里的问题是python注册按键需要很长时间并且给人一种性能不佳的感觉。 我需要知道是否按下了 numpad 4 或 numpad 6 进行导航。在 lib 的 wiki 中提到你不应该使用:
while True:
if keyboard.is_pressed('space'):
print('space was pressed!')
This will use 100% of your CPU and print the message many times.
所以,这是我的代码:
print("Choose Attacker or Defender operator:")
print(" Attacker Defender")
att_state = False
def_state = False
while True:
if keyboard.read_key() == "4":
clear()
print("->Attacker Defender")
def_state = False
att_state = True
if keyboard.read_key() == "6":
clear()
print(" Attacker ->Defender")
att_state = False
def_state = True
if keyboard.read_key() == "5" and att_state:
clear()
printAllOp(attackers)
break
if keyboard.read_key() == "5" and def_state:
clear()
printAllOp(defenders)
break
selection = 0
while att_state:
if keyboard.read_key() == "4":
if selection > 0:
selection -= 1
clear()
printAllOp(attackers, selection)
if keyboard.read_key() == "6":
if selection < 31:
selection += 1
clear()
printAllOp(attackers, selection)
if keyboard.read_key() == "2":
if selection < 23:
selection += 7
clear()
printAllOp(attackers, selection)
if keyboard.read_key() == "8":
if selection > 6:
selection -= 7
clear()
printAllOp(attackers, selection)
if keyboard.read_key() == "5":
clear()
searchOp(attackers, selection, att_source)
att_state = False
break
我也意识到使用 if 和 elif 时的性能是不同的,这就是为什么现在一切都是用 ifs 编写的。
【问题讨论】:
标签: python performance optimization input keyboard