首页 > 解决方案 > Simulating key hold without stopping loop

问题描述

I'm using pynput to simulate key press.

Here's my function i'm using in a loop

def press_hotkey(key, time):
    keyboard.press(key)
    sleep(time) #hold time
    keyboard.release(key)

Sometimes I need to press one key for certain amount of time, for example 2 seconds, but I don't want to stop my loop, as it should continue and press next key if needed.

What would be the most correct way to do that? Is running a function in new thread every iteration a good idea?

标签: pythonpython-multithreadingpynput

解决方案


你可以使用线程模块

import threading

然后像这样在线程中调用你的函数

thread = threading.Thread(target=press_hotkey, args=(desired_key, desired_time))
thread.start()

推荐阅读