[英]Detecting key press in independent (non-blocking) thread in Python
在Python腳本中,我想連續調用一個函數,同時監聽用戶按下ESC鍵,然后退出該程序。
這是我當前的代碼:
import threading
import msvcrt
def wait_for_esc():
while True:
key = ord(msvcrt.getch())
if key == 27:
print("ESC")
exit(0)
def do_something():
while True:
call_function()
thread_1 = threading.Thread(name="wait_for_esc", target=wait_for_esc())
thread_2 = threading.Thread(name="do_something", target=do_something())
thread_1.start()
thread_2.start()
但是,似乎在所有鍵被按下之前, thread_1
阻塞thread_2
。
如何使兩個線程彼此獨立運行?
將目標任務傳遞給線程時,需要傳遞函數對象-而不是調用函數。 您需要刪除函數名末尾的括號。
thread_1 = threading.Thread(name="wait_for_esc", target=wait_for_esc)
thread_2 = threading.Thread(name="do_something", target=do_something)
它應該工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.