tmux: emulate human typing

This commit is contained in:
Théophile Bastian 2020-05-04 00:08:31 +02:00
parent f5987d4048
commit 3b6d0e0fc6
1 changed files with 28 additions and 3 deletions

View File

@ -3,6 +3,7 @@ import multiprocessing
import sys
import random
import libtmux
import time
class TmuxSession:
@ -13,6 +14,7 @@ class TmuxSession:
def __init__(self, session):
self.session = session
self.session_id = session.id
self.keyboard_speed = 0.01
@classmethod
def create_detached(cls, name=None):
@ -49,11 +51,34 @@ class TmuxSession:
""" Send keys to the tmux process. See `man tmux` and `tmux send-keys` for
documentation """
for arg in args:
if arg.endswith(";"):
# Weirdly, `tmux send-keys 'blah;'` doesn't send the semicolon; and so
# does `tmux send-keys ';'`. We must escape it with a backslash.
arg = arg[:-1] + r"\;"
self.session.attached_pane.send_keys(
arg, suppress_history=False, enter=False
)
def type_delay(self):
""" Introduce a small delay, to emulate a human typing """
time.sleep(self.keyboard_speed + random.gauss(0, self.keyboard_speed * 0.1))
# subprocess.run(
# ["tmux", "send-keys", "-t", self.session.id] + list(args), check=True
# )
def type_keys(self, *args):
""" Same as `send_keys`, but emulates a human typing with pauses. This is
**unsafe** for special keys, although the common ones are preserved. """
if self.keyboard_speed == 0:
return self.send_keys(*args)
for arg in args:
if (
arg in ["enter", "escape"]
or arg.startswith("C-")
or arg.startswith("M-")
):
self.send_keys(arg)
self.type_delay()
else:
for char in arg:
self.send_keys(char)
self.type_delay()