Need to register global hotkeys. For example, f4 and f8. With keyboard library while first callback didn't return, the next won't call.
Another words, logs like this
pressed f4
end for f4
pressed f8
end for f8
But I want to like this
pressed f4
pressed f8
end for f4
end for f8
Demo code
# pip install keyboard
from keyboard import add_hotkey, wait
from time import sleep
def on_callback(key):
print('pressed', key)
sleep(5) # emulate long run task
print('end for', key)
add_hotkey("f4", lambda: on_callback("f4"))
add_hotkey("f8", lambda: on_callback("f8"))
wait('esc')
I tried to use asyncio, but nothing changed
pressed f4
end for f4
pressed f8
end for f8
from keyboard import add_hotkey, wait
import asyncio
async def on_callback(key):
print('pressed', key)
await asyncio.sleep(5) # emulate long run task
print('end for', key)
add_hotkey("f4", lambda: asyncio.run(on_callback("f4")))
add_hotkey("f8", lambda: asyncio.run(on_callback("f8")))
wait('esc')
Update 1
Keyboard library's developer gave advise to use call_later function that create new thread for each callback and it's works like I want.
But is there way to do such task in the same thread (use asyncio)? I didn't succeed.
# example with 'call_later' function
from keyboard import add_hotkey, wait, call_later
from time import sleep
def on_callback(key):
print('pressed', key)
sleep(5) # emulate long run task
print('end for', key)
add_hotkey("f4", lambda: call_later(on_callback, args=("f4",)))
add_hotkey("f8", lambda: call_later(on_callback, args=("f8",)))
wait('esc')
Update 2
Now it's look like below (full code on github). I seems that creating new threads in order to wait http request is too heavy operation. Thus I want to use asyncio in current thread and the same time continue handle other hotkeys.
from googleapiclient.discovery import build
from os import getenv
from settings import get_settings
from loguru import logger
import keyboard
class ScriptService():
def __init__(self):
# ...
self._script = AppsScript(id)
self._hotkeys = values["hotkeys"]
def _register_hotkeys(self):
self._add_hotkey(self._hotkeys["reload"], self._on_reload)
for item in self._hotkeys["goofy"]:
k, f = item["keys"], item["function"]
self._add_hotkey(k, self._on_callback, args=(f, k))
def _add_hotkey(self, keys, callback, args=()):
# lambda bug: https://github.com/boppreh/keyboard/issues/493
keyboard.add_hotkey(keys, lambda: keyboard.call_later(callback, args))
def _on_callback(self, function, keys):
response = self._script.run(function)
class AppsScript():
def __init__(self, id: str):
self._name = getenv("API_SERVICE_NAME")
self._version = getenv("API_VERSION")
self._id = id
def run(self, function: str):
body = {"function": function}
with build(self._name, self._version, credentials=get_credentials()) as service:
# http request
return service.scripts().run(scriptId=self._id, body=body).execute()