I want to make the function mouse.record() run until a key is pressed, rather than a mouse button.
The mouse.record() is a function from the python module mouse:
(mouse/__init__.py)
def record(button=RIGHT, target_types=(DOWN,)):
"""
Records all mouse events until the user presses the given button. Then returns the list of events recorded. Pairs well with `play(events)`.
Note: this is a blocking function. Note: for more details on the mouse hook and events see `hook`.
"""
recorded = []
hook(recorded.append)
wait(button=button, target_types=target_types)
unhook(recorded.append)
return recorded
I've thought that I could merge the mouse module with the keyboard module to achieve a function that records the mouse movement until a keyboard event. There is a similar keyboard function that could be handy:
(keyboard/__init__.py)
def record(until='escape', suppress=False, trigger_on_release=False):
"""
Records all keyboard events from all keyboards until the user presses the given hotkey. Then returns the list of events recorded, of type `keyboard.KeyboardEvent`. Pairs well with `play(events)`.
Note: this is a blocking function. Note: for more details on the keyboard hook and events see `hook`.
"""
start_recording()
wait(until, suppress=suppress, trigger_on_release=trigger_on_release)
return stop_recording()
So, to sum it up, what I want to achieve is a function that records the mouse movement until a keyboard event using the Python modules mouse and keyboard.
Is this possible?
解決方案
You can merge both without messing up with the module files:
1) Use mouse.hook() to record events without waiting (like it happens with mouse.record() ). It takes a function and return it that event.
2) Use keyboard.wait(key) to wait for the key to be pressed
3) Use mouse.unhook() to stop recording.
Here is an example code:
import mouse
import keyboard
events = [] #This is the list where all the events will be stored
mouse.hook(events.append) #starting the recording
keyboard.wait("a") #Waiting for 'a' to be pressed
mouse.unhook(events.append) #Stopping the recording