[英]How can I link a variable between two running python programs?
我正在使用 Pynput 創建一個程序,簡而言之,該程序將在按住某個鍵的同時執行某些操作。
在對 Pynput 進行了一些研究之后,我發現沒有辦法,而且似乎沒有計划的方法可以在按住鍵的同時做某事,所以我正在設計我的方法。
我的計划是讓兩個 Python 腳本同時運行,它們之間有一個不斷更新的變量鏈接。 這是因為 while 循環在一個程序中使用時會停止 Pynput 偵聽器。 其中一個腳本將監聽鍵盤並相應地更新變量,另一個將實際執行結果。
唯一的問題是我不知道如何在兩個正在運行的腳本之間主動鏈接變量,互聯網上沒有任何內容讓我知道如何這樣做(我嘗試導入其他腳本和東西,但不僅是這很難,因為我使用的是 Mac,但它沒有主動傳遞變量)。
目前,我的代碼看起來有點像這樣:
(監聽器腳本)
from pynput import keyboard
doThing = 0
def on_press(key):
doThing = 1
def on_release(key):
doThing = 0
def startListener():
listener = keyboard.Listener(
on_press=on_press,
on_release=on_release)
listener.join()
(做某事的腳本)
while True:
if doThing == 1:
print('Thing')
我想在它們之間鏈接的變量是 doThing,但同樣我不知道我將如何以這種方式實際設置變量。 我正在考慮使用 JSON,但我不知道這是否是最好的方法。
謝謝!
您已經考慮使用臨時文件? 這是示例:
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()
在第二個腳本中:
def truncate_file():
with open("temp","w"):
pass
while True:
doThing = len(open("temp", "r").read()) > 0
if doThing:
print('Thing')
truncate_file()
這是一個使用線程的示例。 這允許 Python 運行兩個(或更多)單獨的線程,每個線程同時做不同的事情。 (從技術上講,它們實際上不是同時發生的,而是交替發生的,但這在這種情況下並不重要)。
在一個線程中,您會監聽按鍵操作。 在另一個線程中,您檢查關鍵狀態並做出適當的反應。
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")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.