我正在開發一個程式,我需要一個用戶輸入進行選擇,而不是專注于控制臺視窗。我想使用的方法是在小鍵盤上使用鍵盤輸入。我找到了這個庫Python 鍵盤庫來實作這一點。我的問題是 python 需要很長時間來注冊按鍵并且給人一種性能不佳的感覺。我需要知道是按小鍵盤 4 還是小鍵盤 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 撰寫的原因。
uj5u.com熱心網友回復:
您可以為每次迭代設定微秒或毫秒睡眠,10 微秒睡眠,
import time
while True:
if keyboard.is_pressed('space'):
print('space was pressed!')
time.sleep(seconds/100000.0)
這應該會減少您的 CPU 使用率,因此應該會提高整體性能。
更好的是,使用像keyboard.on_press這樣的鍵盤鉤子。這是正確的做法。
此外,如果您可以系結到作業系統(Windows 或特定版本的 Linux 發行版),您可以將您的 python 編譯為 binary,這使用 PyInstaller 非常簡單。
uj5u.com熱心網友回復:
您根本不應該使用keyboard.read_key(),而是用于keyboard.add_hotkey()注冊修改全域狀態的回呼。
例子:
att_state = False
def_state = False
def set_state(new_state):
att_state = (new_state == 'att')
def_state = not att_state
# add code to update display
# Register callbacks for 4 and 6
keyboard.add_hotkey('4', lambda: set_state('att'))
keyboard.add_hotkey('6', lambda: set_state('def'))
# Process keystrokes until '5' is pressed
keyboard.wait(hotkey='5')
注意:我從來沒有使用過這個庫,也沒有測驗過這個代碼(沒有 Windows)所以買家要當心:)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/389802.html
上一篇:SQLjoin性能操作順序
