I made a program that launches a short script each time a certain key combination is pressed. I am using a thread that utilise pyHook in the following manner:
def logic():
global running
hm = HookManager()
hm.KeyDown = captureF
hm.HookKeyboard()
while(running):
pythoncom.PumpWaitingMessages()
return
where captureF
is a function that tests if the certain key combination is pressed and then if pressed launches the script.
on the main thread i am running a windows tray gui that includes options and exit (upon pressing exit it set the flag running
to false, resulting the logic thread to finish).
The problem i am facing right now is that the CPU usage is constantly high when the program is launched (even when the script is not launched), i guess the problem is in the way i am testing for keyboard input but i am not sure how to do it in a more efficient way.
Thanks for the help in advance.
The problem is that your polling hogs the CPU: PumpWaitingMessages
checks for messages and returns immediately if no messages (it is non-blocking)
You have to insert some kind of delay. The simplest would be:
import time
while(running):
pythoncom.PumpWaitingMessages()
time.sleep(0.01)
1/100th second ensures good reactivity and gives breathing space to the CPU. I'll let you adjust the value. The higher you set the value, the less reactive your polling will be.
However, if you don't need any control on your loop, you could as well use the blocking pythoncom.PumpMessages()
call, without a loop.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.