Banner of Building xdo: A Scheduled Desktop Automation CLI in Python

Building xdo: A Scheduled Desktop Automation CLI in Python


Category: Programming » Python

📅 December 06, 2026   |   👁️ Views: 1

Author:   mosaid

In the previous article, I used Bash, sleep, and xdotool to schedule a single desktop action. The mechanism was deliberately small: prepare the application, wait for a known interval, and send a keyboard or mouse event.

That approach is useful precisely because it has almost no architecture. A few shell commands are enough when the task is one delayed action. But once the requirements start accumulating—absolute execution times, multiple actions, reusable scripts, repetitions, window checks, a countdown, dry-run mode, and input backends—the shell script begins to become a program with an implicit parser and execution model.

I decided to move that responsibility into a small Python command-line application called xdo. It still uses xdotool to interact with an X11 desktop. Python does not replace the underlying input mechanism; it provides a structure around it.

The important change is not the language. It is the separation of scheduling, parsing, validation, and input delivery into components that can evolve independently.

From a delayed command to a reusable tool

The original shell workflow had a straightforward contract: wait, then execute a command. The next version needed to describe a sequence of operations and determine when that sequence should begin.

The current implementation supports two scheduling modes: a relative delay with --delay, and an absolute local time with --at. It can execute shortcut flags or a script file, repeat a sequence, show a countdown, perform a dry run, and optionally check for windows before execution.

ConcernInitial shell approachxdo
TimingsleepRelative delay or absolute target time
ActionsCommands written directly in BashValidated script commands
ReuseCopy or edit the shell scriptInline text, file, or standard input
ExecutionShell controls the sequenceDedicated runner executes parsed steps
TestingRun against the desktopDry-run mode prints the planned steps
Window handlingUsually relies on current focusFind, focus, wait for, or require a matching window

This is not intended to compete with browser automation frameworks or application APIs. The scope is narrower: schedule ordinary desktop input and make the workflow repeatable without requiring a large automation stack.

Architecture: four responsibilities

The project is intentionally split into a small number of modules. Each module owns one part of the execution path.

xdo module architecture The CLI parses options and connects the parser, runner, and backend. The script parser produces validated steps. The runner schedules and executes them through the backend, which delegates input to xdotool. cli.pyarguments · validation · wiring script.pyparse text → validated Step objects runner.pypreflight · wait · execute · repeat backend.pyinput interface · xdotool implementation script inputCLI flags
The main execution path. The CLI coordinates the modules; it does not implement mouse or keyboard operations itself.

cli.py owns argument parsing and application wiring. script.py turns a small textual language into validated steps. runner.py handles preflight checks, waiting, repetition, and dispatch. backend.py defines the input interface and implements it with xdotool.

The direction of dependency matters. The runner depends on the backend interface, not on the details of every xdotool command. The parser does not know about the desktop. The CLI knows how to construct the pieces, but it should not become the place where all behavior accumulates.

The script language: describe actions, do not execute while parsing

A central design decision was to avoid translating script lines directly into backend calls as they are read. Instead, parsing produces a list of immutable Step objects. Each step records the command, its already-coerced arguments, the source line number, and the original line.



from dataclasses import dataclass

@dataclass(frozen=True)
class Step:
    command: str
    args: tuple
    lineno: int
    raw: str

This intermediate representation creates a useful boundary. A script can be parsed and rejected before the runner waits or sends any input. The runner receives structured data rather than having to interpret strings while executing.

The parser supports commands such as:



# Move and click
move 500 300
click left

# Keyboard and text
key ctrl+l
paste https://example.org
key Return

# Timing and window management
sleep 2
wait-window "Example Browser" 30
window "Example Browser"

Scripts can be supplied inline, read from a file using @FILE, or read from standard input using -. For example:



xdo --delay 15 --script @workflow.xdo
cat workflow.xdo | xdo --at 23:45 --script -

Why use shlex?

Most commands have a predictable number of arguments. For those, shlex.split() provides shell-like tokenization without invoking a shell. It handles quoted arguments such as a window title containing spaces:



argv = tuple(shlex.split(rest))

There is an exception: commands such as type, paste, notify, and exec treat the rest of the line as their payload. Splitting those arguments would alter the text the user intended to send. The parser therefore identifies these commands and preserves the remainder of the line.

It also supports semicolon-separated commands, while respecting quoted semicolons. That small amount of custom parsing is justified because a naïve line.split(';') would break a command whose quoted text contains a semicolon.

Validation and coercion

The parser validates argument counts and converts values before creating a step. Coordinates become integers, durations become floats, mouse buttons are normalized, and scroll directions are checked against a fixed set. Errors include the original line number.

This is a practical form of an intermediate representation: by the time a Step reaches the runner, its syntax has been checked and its arguments have the expected basic types. It does not prove that the desktop action will succeed, but it removes many avoidable runtime errors.

The backend: isolate the input mechanism

The backend module defines an abstract Backend interface. It describes the operations the runner needs: moving, clicking, typing, pasting, scrolling, dragging, holding keys, and interacting with windows.



from abc import ABC, abstractmethod

class Backend(ABC):
    @abstractmethod
    def move(self, x: int, y: int, smooth: float = 0.0) -> None: ...

    @abstractmethod
    def click(self, button: int = 1, count: int = 1) -> None: ...

    @abstractmethod
    def key(self, combo: str) -> None: ...

    @abstractmethod
    def type(self, text: str, delay: float = 0.02) -> None: ...

    @abstractmethod
    def paste(self, text: str) -> None: ...

XdotoolBackend implements that interface by invoking xdotool through subprocess.run(). The runner does not need to know whether a click is implemented by xdotool, another Linux input tool, or a future backend. It only calls backend.click().

This is a modest abstraction, not a claim that all input systems are interchangeable. X11 and Wayland have different security and input-injection models. A future backend would need to account for those differences, and some operations may not map one-to-one. The interface gives the project a place to put those differences rather than scattering backend-specific conditionals throughout the runner.

Why subprocess rather than a Python X11 binding?

For this project, xdotool is already the working input tool. Calling it as a subprocess keeps the implementation small and delegates low-level X11 interaction to a utility designed for that purpose. It also means the dependency is explicit: xdotool must be installed and available in PATH.

The backend checks that dependency during initialization. Its internal helper centralizes command execution and converts a failed xdotool invocation into a BackendError. That gives the runner one consistent error type to handle.

Text entry has two paths. The type command uses xdotool's typing facility. The paste command writes to the clipboard with xclip or xsel, then sends Ctrl+V. Clipboard-based paste is useful for Unicode text; if neither clipboard utility is installed, the current implementation falls back to simulated typing and logs a warning.

That fallback is convenient but not equivalent. The implementation itself notes that xdotool typing may not handle non-ASCII text reliably. A tool should make such limitations visible rather than silently promising identical behavior.

The runner: preflight, wait, execute

ScheduledRunner is the execution engine. It receives the backend, parsed steps, target time, repetition settings, and execution options. Its public run() method follows a deliberately simple lifecycle:



def run(self) -> int:
    try:
        self.preflight()
        self.wait()
        self.execute()
    except KeyboardInterrupt:
        print("\\nCancelled.")
        return 130
    except (BackendError, RunnerError) as exc:
        LOG.error("%s", exc)
        return 1
    return 0

The order is important. Preflight happens before the potentially long wait. A missing required window or a disallowed command should fail immediately, not after the user has left the machine waiting for several hours.

Relative and absolute scheduling

The CLI computes a target datetime. With --delay, it adds a duration to the current local time. With --at, it accepts a clock time or a date and time. If only a clock time is supplied and that time has already passed today, the parser rolls the target forward to the next day.

The runner then repeatedly calculates the remaining time from the target datetime. It sleeps for at most one second per iteration, updating the countdown when enabled. This is preferable to decrementing a counter and assuming every loop takes exactly one second: the displayed remaining time is recalculated against the target, so small delays in printing do not accumulate as timer drift.

This is still a user-space scheduler, not a real-time guarantee. The process can be delayed by system load, suspension, or session changes. The target determines when the runner should begin; it cannot guarantee that the operating system will schedule the process at an exact millisecond.

Preflight checks and window state

The current runner has three related window commands:

• require-window: verify that a matching window exists before the countdown begins, then check again when the step is reached.

• wait-window: wait for a matching window to appear, with a configurable timeout.

• window: attempt to focus a matching window.

These checks reduce dependence on whichever window happens to be active, but they do not establish application-level readiness. A browser window can exist while the page is still loading; a title can match the wrong tab or a stale dialog. Window matching is a useful desktop-level condition, not a semantic understanding of the application.

Repetition and cancellation

The runner can repeat the full sequence a configured number of times, with an interval between repetitions. It also handles Ctrl+C through KeyboardInterrupt and installs a SIGTERM handler that marks execution as cancelled between steps.

There is an important limitation to the current SIGTERM handling: cancellation is checked between steps, not during every backend operation. A long-running operation or a held key has its own cleanup requirements. The backend's hold() implementation uses try/finally to release a key even if the wait is interrupted, which is a good example of putting cleanup next to the operation that requires it.

Dry-run as a development tool

A desktop automation tool should make it possible to inspect a sequence before it starts sending input. The current --dry-run mode still performs the scheduling wait, but prints each action instead of dispatching it to the backend.



xdo --delay 10 --dry-run --script @workflow.xdo

This is useful for checking ordering and repetition without changing the desktop. It is not a full simulation: it does not prove that coordinates are correct, that a window will appear, or that the target application will accept the input. In the current implementation, preflight window checks still consult the real desktop, while the action handlers are skipped in dry-run mode.

CLI design: shortcuts and scripts share one path

The CLI offers convenience flags such as -c for click, -k for key, and -t for text. Rather than implementing a second execution path for these flags, _build_quick_script() converts them into script lines and sends them through the same parser as a supplied script.

This avoids maintaining two separate implementations of validation and execution. A quick command and a script command become the same internal Step representation.



# A short one-off action
xdo --delay 5 --click --key Return

# A reusable workflow
xdo --at 22:30 --script @nightly-workflow.xdo

# Inspect the sequence without dispatching input
xdo --dry-run --script @nightly-workflow.xdo

One detail to keep in mind: the quick shortcuts are documented and implemented as actions that run before the supplied script. Their ordering is therefore part of the CLI contract, not an incidental property of argparse.

Execution boundaries and safety

Desktop automation can have consequences beyond the terminal process. A click may submit a form, a key may confirm a dialog, and a pasted string may be sent to the wrong application if focus changes. The tool cannot infer whether an action is harmless. The operator must review the target and the sequence.

The script language includes an exec command for running a shell command. Because that is a different capability from sending desktop input, the implementation requires the explicit --allow-exec option. The runner rejects scripts containing exec during preflight unless the option is present.

This is an opt-in guard, not a sandbox. Once enabled, the command is passed to subprocess.run(..., shell=True). A script containing exec should therefore be treated as trusted code, not as a harmless data file. Do not enable it for scripts from untrusted sources.

There are also two implementation details worth tightening before treating the current version as a polished release:

• Log redaction: the CLI help says file logging redacts type and paste text, but the runner currently logs step.raw at INFO level. That can expose the payload in logs. The logging implementation should redact sensitive command arguments before the feature is described as redacting them.

• Beep timing: the CLI help says --beep rings just before execution, but the current call occurs before runner.run(), which includes the preflight and scheduled wait. Move the beep into the runner immediately before dispatch if that timing is intended.

These are not architectural failures; they are examples of why documentation should describe what the code actually does, and why user-facing promises need to be tested against the execution path.

Packaging and module execution

The project currently has a __main__.py that imports main from cli. That may work when the files are run from a directory placed on Python's import path, but package execution should use package-relative imports and a consistent package name. Before distributing the project as an installable package, I would also add a proper build configuration and a console-script entry point so users can invoke xdo without relying on the working directory.

The manifest's package docstring currently names the project schedclick, while the CLI program name is xdo. That naming should be made consistent before publishing. These small packaging details do not change the runtime architecture, but they matter when moving from a local utility to a tool other people can install and maintain.

Performance and operational constraints

The Python layer is not doing expensive computation. It parses a small text file, stores a list of steps, waits using short sleeps, and launches xdotool subprocesses when actions are required. For ordinary desktop workflows, the main cost is the input operations and process launches, not the parser or the dataclass representation.

Smooth cursor movement is the notable exception: the backend divides a movement into a number of intermediate positions and invokes xdotool repeatedly. The number of steps is proportional to the requested duration, at roughly sixty steps per second. That makes smooth movement visibly gradual, but it also means more subprocess calls than a direct move.

The scheduler also remains tied to the graphical session. The machine must stay awake, the relevant display session must remain available, and the target application must be in a usable state. Moving the timer into a system service would not remove those dependencies. A service can schedule a process; it cannot make an interactive desktop session reliable after logout or suspension.

What I would improve next

The current design provides a useful foundation, but there are several clear next steps:

• Tests: unit-test script splitting, quoting, argument coercion, time parsing, and preflight behavior. A fake backend would allow runner tests without generating real desktop input.

• Backend selection: make backend choice explicit once a second implementation exists. Avoid adding speculative abstraction layers before there is a real backend to support.

• Packaging: add a proper package configuration, consistent imports, and a console entry point.

• Structured logging: redact text payloads by default and distinguish planned actions from actions that were actually dispatched.

• Better state checks: keep window checks as a desktop-level primitive, while leaving application-specific readiness to integrations that can inspect meaningful state.

• Execution reporting: record step start, completion, and failure in a way that does not leak typed or pasted content.

I would not add all of these at once. The next useful improvement is a test suite around the parser and runner. Those components contain most of the project's own logic and can be tested without a graphical session. The xdotool backend can then be covered with a smaller set of integration tests in an X11 environment.

Final thoughts

The first version solved one problem with two commands: wait, then send input. The Python version exists because the workflow grew beyond that narrow contract. It needed a reusable command language, a clear execution lifecycle, validation before waiting, and a boundary between scheduling logic and the mechanism that talks to the desktop.

A small tool becomes maintainable when its responsibilities are explicit—not when its codebase becomes large.

xdo is still a focused utility built on top of xdotool. It does not understand the applications it controls, and it does not guarantee that a scheduled interaction will succeed. What it does provide is a structured way to describe and run desktop input sequences, with enough validation and separation to make future changes manageable.

That is the natural continuation of the original Bash experiment: not replacing a simple script for the sake of using Python, but introducing structure only when the requirements justify it.


← Delayed Desktop Automation with Bash and xdotool

Leave a comment

5000 characters max.