Ich habe einen Hintergrund Thread, der gelegentlich Tastatureingabe benötigt. Der Haupt-Thread liest jedoch auch Eingaben von der Tastatur. Wenn ich input()
rufe, erhält der Hauptfaden die Eingabe. Ich habe versucht, Schlösser zu benutzen, aber sie funktionieren nicht für mich.Wie liest man Tastatureingaben von einem Hintergrundthread in Python?
Hauptprozess (nur ein Teil des Codes):
def smth(aff):
af = aff
lock = threading.Lock()
print(lock)
Peer.setlock(lock)
while True:
lock.acquire(blocking=True, timeout=-1)
inp = input()
parse(inp)
lock.release()
Thema Code:
global lock
def setlock(j):
print("Setting lock ", j)
global lock
lock = j
print("Lock status: ", lock.locked())
success = lock.acquire(blocking=True, timeout=-1)
print(success)
print("You are recieving a file, type y to confirm saving:")
print(lock)
if input() == "y":
path = ""
print("Input path:")
path = input()
if os.path.isfile(path):
print("File already exists. Type y to confirm:")
if not input()=="y":
return
handle = open(path, "wb")
filewriters[transferID] = filewg(handle, numberOfPackets)
filewriters[transferID].send(None)
lock.release()
print(lock)
Der gesamte Code befindet here.
Ich schrieb nur ein weiteres minimal Beispiel und Schlösser scheinen hier zu arbeiten: Import
lock = threading.Lock()
def th():
while True:
lock.acquire(blocking=True, timeout=-1)
print("Thread prints ", input())
lock.release()
tic = threading.Thread(target=th)
tic.start()
while True:
lock.acquire(blocking=True, timeout=-1)
print("Main prints ", input())
lock.release()
Versuchen Sie, ein [minimales, vollständiges und überprüfbares Beispiel] (http://stackoverflow.com/help/mcve) des Problems zu veröffentlichen. Ihr Code sieht merkwürdig aus, da außer der Sperre keine Threading-Konstrukte vorhanden sind. Offensichtlich haben Sie einige wichtige Informationen weggelassen. – CAB
Der gesamte Code befindet sich [hier] (https://github.com/Creator/P2P). – Creator