简体   繁体   中英

Python loop waiting to detect keyboard key and high cpu usage

Hi guys i'have made this python code to understand if a key is being pressed but it uses a lot of cpu.

I have tried using sleeping time , but this affects the key detection.

if __name__ == '__main__':
    a = b = 1
    x = [0] * 4
    y = [0] * 4
    Qpremuto = False
    while (True):

        i = 0

        if keyboard.is_pressed('q'):
            Qpremuto = True

            print(i)

            x[i], y[i] = pyautogui.position()
            print(pyautogui.position())
            a = 0

            break
    time.sleep(0.2) # Not good , affects key detection

there is a way not to use the cpu but a lighter way ?

I'm not sure what do you mean by lighter way, but if you don't want your code to "pause" you can create a thread to do the loop in the background:

import threading

def thread_function():
    while (True):
            i = 0
            if keyboard.is_pressed('q'):
                Qpremuto = True
                print(i)

                x[i], y[i] = pyautogui.position()
                print(pyautogui.position())
                a = 0
                break

In main , simply call:

thread = Thread(target = thread_function)
thread.start()

If you want the thread to stop:

thread.join()

If using windows, the old kbhit and getch C functions can be used from the msvcrt library.

import msvcrt
import time

print('Press q to exit...')
while True:
    if msvcrt.kbhit() and msvcrt.getch() == b'q':  # can omit the getch if 'any key'
        # ... do something here before exit
        break
    # ... do something here in every loop
    time.sleep(0.1)  # 100ms sampling -> low CPU usage
        
# Empty Keyboard Buffer        
while msvcrt.kbhit():
    msvcrt.getch()

The sleep time can be adjusted, depending if there is any task to do on every loop, and on the workload performed.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM