キーボードとマウスの入力を記録と再現するコードを書く

悪く使わないことを前提に作る。
Pythonで作り、keyboardモジュールとmouseモジュールを使う。
これらのモジュールを使って操作の記録をしているときは他の処理にロックがかかるため、threadingを使う。

…しかし、今の私のスキルは十分でなかったw
検索すると同じことを試みた方がいて、その回答を使わせていただく。
How to record mouse and keyboard movement simultaneously with Python?
しかし、この回答の方法はキーボードの入力の再現とマウスの入力の再現を同時にスタートさせるため、正しい順序にならない。
少しコードを変更して、タイミングが合うようにdelayを設ける。
import keyboard, mouse

mouse_events = []

mouse.hook(mouse_events.append)
keyboard.start_recording() # Starting the recording

print('Hit ESC key to stop recording')
keyboard.wait('escape')

mouse.unhook(mouse_events.append)
keyboard_events = keyboard.stop_recording() # Stopping the recording. Returns list of events
print(keyboard_events, mouse_events)

'''
# mouse.play() will start after keyboard.play() done.
keyboard.play(keyboard_events)
mouse.play(mouse_events)
'''

# Using threading can play the both at the same time, but they are not synchronized.
# Use sleep to wait for the different time.

from time import sleep
import threading
from threading import Thread
threads = []

def play(thread, delay=0.0):
	global threads
	sleep(delay)
	threads.append(thread)
	thread.start()

if len(keyboard_events) > 0 and len(mouse_events) > 0:
	started_at = min(keyboard_events[0].time, mouse_events[0].time)
	# Keyboard threadings
	thread = Thread(target=lambda:keyboard.play(keyboard_events))
	t = Thread(target=play, args=(thread, keyboard_events[0].time-started_at))
	threads.append(t)
	t.start()
	# Mouse threadings
	thread = Thread(target=lambda:mouse.play(mouse_events))
	t = Thread(target=play, args=(thread, mouse_events[0].time-started_at))
	threads.append(t)
	t.start()
else:
	# Keyboard threadings
	thread = Thread(target=lambda:keyboard.play(keyboard_events))
	t = Thread(target=play, args=(thread,))
	threads.append(t)
	t.start()
	# Mouse threadings
	thread = Thread(target=lambda:mouse.play(mouse_events))
	t = Thread(target=play, args=(thread,))
	threads.append(t)
	t.start()

# Waiting for the threadings to be completed
for thread in threads: thread.join()
📁./Documents/desktop_recorder.0.zip
2019/12/12 00:15
タグ