1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.
  2. Anuncie Aqui
    Anuncie aqui você Também: fdantas@4each.com.br

[Python] Python keyboad input simulation fast

Discussão em 'Python' iniciado por Stack, Maio 7, 2025.

  1. Stack

    Stack Membro Participativo

    Is it possible to bump up the speed of keyboard inputs using a normal python script or do I have to switch to C# or Rust? The goal is to simluate movement in a game where it comes down to ms. Below is the output of a quick analysis of the planned time and the actual time python needed to simulate the movement:

    planned_s actual_s action
    0.03125 0.0616778 (key, w)
    0.34375 0.8544916 (mouse, left)
    0.59375 1.3620928 (key, space)
    0.625 1.4259067 (mouse, left)
    0.703125 1.5822482 (key, w)

    The current script uses the python packages keyboard and mouse.

    def press_action(action, down):
    kind, key = action

    if kind == "key":
    if down:
    keyboard.press(key)
    else:
    keyboard.release(key)

    elif kind == "mouse":
    if down:
    mouse.press(button=key)
    else:
    mouse.release(button=key)


    The DB stores sets of actions that are then passed to the replay_action_sequence. These look as follows:


    {'actions': [['mouse', 'left'], ['key', 'space'], ['key', 'shift']], 'duration_ms': 15.625}, {'actions': [['key', 'space'], ['key', 'shift']], 'duration_ms': 109.375}, {'actions': [['key', 'shift']], 'duration_ms': 31.25}]
    ​

    def replay_action_sequence(action_intervals):
    held = set()
    for step in action_intervals:
    # turn each action-list into a tuple, then build set
    current = { tuple(a) for a in step["actions"] }
    dur_s = step["duration_ms"] / 1000.0

    for a in held - current:
    press_action(a, False)
    for a in current - held:
    press_action(a, True)

    held = current
    precise_sleep(dur_s)

    for a in held:
    press_action(a, False)

    def precise_sleep(seconds: float):
    """Sleep for `seconds`, busy‐wait last 1ms for accuracy."""
    if seconds <= 0:
    return
    if seconds > 0.002:
    time.sleep(seconds - 0.001)
    end = time.perf_counter() + seconds
    while time.perf_counter() < end:
    pass


    Based on some research and input from ChatGPT I have inserted these lines:

    try:
    windll.winmm.timeBeginPeriod(1)
    psutil.Process().nice(psutil.HIGH_PRIORITY_CLASS)
    except Exception:
    pass


    But they don't seem to have much impact.

    As is quite obvious from my question I am still a beginner and would have thus preferred to stick with python. If you say it is not feasible that way, however, I would switch to C# probably as I at least had some contact with that. The C# script or resulting .exe could still be called from python though, right?

    Continue reading...

Compartilhe esta Página