0

In my case, I want to hook the keyboard keys that is pressed. And when I press "0", I want to kill the terminal.

Both functions should work at the same time. But my code doesn't work. What is wrong with this code?

import keyboard 
import asyncio


def sleep(a):
    rand1 = random.uniform(0, 0.009)
    rand2 = random.uniform(0.01, 0.02)
    result = random.uniform(rand1, rand2)
    
    asyncio.sleep(a + result)


async def record_start():
    while True:
        k = keyboard.read_key() 
        k = keyboard.read_key()
        print(k)  
        

async def record_stop():
    while True:
        if keyboard.is_pressed('0'):
            
            print('stop')
            sleep(1)
            exit()     
          


async def main():
    await asyncio.gather(
        record_stop(),
        record_start(),
    )


asyncio.run(main())

I tried out using another modules. And I assume that problem is modules or way to use "while"

  • Does this answer your question? [How to async handle callback from keyboard hotkeys?](https://stackoverflow.com/questions/69371075/how-to-async-handle-callback-from-keyboard-hotkeys) – Amin S Feb 08 '23 at 04:01

2 Answers2

0

your record_start function never gives a chance to any other async code to run. Introduce an awaiting call in it, like await asyncio.sleep(.01) in it (it may be sleep(0) but I'd advise a larger interval), and things should work.

jsbueno
  • 99,910
  • 10
  • 151
  • 209
0

I just solved this issue. It doesn't need to use 'asyncio' module.

instead, I run this code with 'threading' module.

from threading import Thread
import os
def thread_1():
 while True:
    start_time = time.time()
    k = keyboard.read_key() 
    k = keyboard.read_key()
    print("sleep(%s)" % round(time.time() - start_time, 3))
    print("press('%s')" % k) 

def thread_2():
 while True:
    if keyboard.is_pressed('0'):
        print('stop')
        pid = os.getpid()
        os.kill(pid, 2)  





if __name__ == "__main__":
 t1 = Thread(target=thread_1)
 t2 = Thread(target=thread_2)

 print('start')
 t1.start()
 t2.start()