2 回答

TA貢獻(xiàn)1111條經(jīng)驗(yàn) 獲得超0個(gè)贊
這是一個(gè)使用線程的示例。這允許 Python 運(yùn)行兩個(gè)(或更多)單獨(dú)的線程,每個(gè)線程同時(shí)做不同的事情。(從技術(shù)上講,它們實(shí)際上并不是同時(shí)發(fā)生的,而是交替發(fā)生的,但這在這種情況下并不重要)。
在一個(gè)線程中,您監(jiān)聽按鍵。在另一個(gè)線程中,您檢查關(guān)鍵狀態(tài)并做出適當(dāng)反應(yīng)。
import threading
from pynput import keyboard
class KeyCheckThread(threading.Thread):
def __init__(self):
super(KeyCheckThread, self).__init__()
self.doThing = 0
def on_press(self, key):
self.doThing = 1
def on_release(self, key):
self.doThing = 0
def run(self):
with keyboard.Listener(on_press=self.on_press, on_release=self.on_release) as listener:
listener.join()
listenerThread = KeyCheckThread()
listenerThread.start()
while(True):
if listenerThread.doThing == 1:
print("doThing")

TA貢獻(xiàn)1884條經(jīng)驗(yàn) 獲得超4個(gè)贊
您已經(jīng)考慮使用臨時(shí)文件了嗎?這是示例:
from pynput import keyboard
doThing = 0
def generate_variable(var):
with open("temp", "a") as temp:
temp.write(str(var))
def on_press(key):
generate_variable(1)
def on_release(key):
doThing = 0
def startListener():
listener = keyboard.Listener(
on_press=on_press,
on_release=on_release)
listener.join()
在第二個(gè)腳本上:
def truncate_file():
with open("temp","w"):
pass
while True:
doThing = len(open("temp", "r").read()) > 0
if doThing:
print('Thing')
truncate_file()
添加回答
舉報(bào)