如何在Python中从全局范围内的线程执行代码?

问题描述 投票:0回答:1

我想要一个线程来检查键盘按钮是否被按下,如果是,则它会休眠全局作用域/主执行的执行

例如:

import time
import multiprocessing
import keyboard

def check_if_button_is_pressed(button):
    while True:
        if keyboard.is_pressed(button):
            time.sleep(100) # I want this line of code to run in the main function

def main():
    multiprocessing.Process(target=check_if_button_is_pressed, args=("g",)).start()

    while True:
        print("global execution")

if __name__ == "__main__":
    main()

当按下 g 时,我希望它停止打印“全局执行”100 秒。

python multithreading keyboard
1个回答
0
投票

你需要使用某种沟通方式。常用的方法是使用

Queue
在线程之间进行通信。它依赖于主线程轮询主循环中的队列并在其中有东西时做出反应。

在本例中,我这样做是为了将睡眠时间放入队列中,主线程会查看是否有东西在,如果有,则使用该值作为

time.sleep
函数的输入。

import keyboard
import time
import threading
from queue import Queue, Empty

q = Queue()


def check_if_button_is_pressed(button, queue):
    while True:
        if keyboard.is_pressed(button):
            queue.put(100)
            time.sleep(0.1)  # Added since otherwise one keypress would add a lot of elements to the key


threading.Thread(target=check_if_button_is_pressed, args=("g", q)).start()

while True:
    try:
        ret = q.get(block=False)
    except Empty:
        ret = None
    if ret is not None:
        time.sleep(ret)
    print("global execution")

© www.soinside.com 2019 - 2024. All rights reserved.