我希望一个函数与后台的其他进程并行运行,这样当我单击ctrl+a时,letter就会被设置为a。然而,我尝试使用多处理,它不会从函数中转移,而且当我单击一次ctrl+b时,它会产生一个死循环。
from multiprocessing import Process
import keyboard as kb
def AOrB():
while True:
if kb.is_pressed("ctrl+a"):
letter = "a"
print(letter)
if kb.is_pressed("ctrl+b"):
letter = "b"
print(letter)
def main():
# Other codes
p = Process(target=AOrB())
p.start()
p.join()
# Other codes
if __name__ == '__main__':
main()
点击ctrl+b一次现在产生:
b
b
b
b
b
b
b
b
问题是在Process
中将函数指定为目标时调用该函数。这会导致程序挂在Process(target=AOrB())
试试这个:
p = Process(target=AOrB)
编辑:
以下是完整的代码,只输出一次密钥:
from multiprocessing import Process
import keyboard as kb
letter = ""
def AOrB():
global letter
while True:
if kb.is_pressed("ctrl+a"):
if letter != "a":
letter = "a"
print(letter)
if kb.is_pressed("ctrl+b"):
if letter != "b":
letter = "b"
print(letter)
def main():
# Other codes
p = Process(target=AOrB)
p.start()
p.join()
# Other codes
if __name__ == '__main__':
main()