Skip to content

ExecCommand

Base classes

Name Children Inherits
SlashedCommand
slashed.commands
Base class for declarative commands.

⋔ Inheritance diagram

graph TD
  1418435899["system.ExecCommand"]
  807245086["commands.SlashedCommand"]
  900363605["base.BaseCommand"]
  925645236["abc.ABC"]
  2751680898["builtins.object"]
  807245086 --> 1418435899
  900363605 --> 807245086
  925645236 --> 900363605
  2751680898 --> 925645236

🛈 DocStrings

Bases: SlashedCommand

Execute a system command and capture its output.

Usage

/exec [args...]

Waits for the command and prints its output, without blocking the event loop. Arguments are passed through unchanged (/exec git -C dir status).

Source code in src/slashed/builtin/system.py
class ExecCommand(SlashedCommand):
    """Execute a system command and capture its output.

    Usage:
      /exec <command> [args...]

    Waits for the command and prints its output, without blocking the event loop.
    Arguments are passed through unchanged (``/exec git -C dir status``).
    """

    name = "exec"
    category = "system"
    raw_args = True
    timeout: float | None = None
    """Seconds after which the process is killed (None: no limit)."""

    def get_completer(self) -> PathCompleter:
        """Get path completer for executables."""
        return PathCompleter(directories=True, files=True)

    async def execute_command(
        self,
        ctx: CommandContext[Any],
        command: str,
        *args: str,
    ) -> None:
        """Execute system command and wait for it."""
        try:
            process = await asyncio.create_subprocess_exec(
                command,
                *args,
                stdin=subprocess.DEVNULL,
                stdout=subprocess.PIPE,
                stderr=subprocess.PIPE,
            )
        except FileNotFoundError as e:
            msg = f"Command not found: {command}"
            raise CommandError(msg) from e
        try:
            stdout_b, stderr_b = await asyncio.wait_for(process.communicate(), self.timeout)
        except TimeoutError as e:
            process.kill()
            await process.wait()
            msg = f"Command timed out after {self.timeout} s"
            raise CommandError(msg) from e
        except asyncio.CancelledError:
            process.kill()
            await process.wait()
            raise
        stdout = stdout_b.decode(errors="replace")
        stderr = stderr_b.decode(errors="replace")
        if process.returncode:
            msg = f"Command failed with exit code {process.returncode}"
            if stderr:
                msg = f"{msg}\n{stderr}"
            raise CommandError(msg)
        if stdout:
            await ctx.print(f"```\n{stdout.rstrip()}\n```")
        if stderr:
            await ctx.print(f"**stderr:**\n```\n{stderr.rstrip()}\n```")

timeout class-attribute instance-attribute

timeout: float | None = None

Seconds after which the process is killed (None: no limit).

execute_command async

execute_command(ctx: CommandContext[Any], command: str, *args: str) -> None

Execute system command and wait for it.

Source code in src/slashed/builtin/system.py
async def execute_command(
    self,
    ctx: CommandContext[Any],
    command: str,
    *args: str,
) -> None:
    """Execute system command and wait for it."""
    try:
        process = await asyncio.create_subprocess_exec(
            command,
            *args,
            stdin=subprocess.DEVNULL,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
        )
    except FileNotFoundError as e:
        msg = f"Command not found: {command}"
        raise CommandError(msg) from e
    try:
        stdout_b, stderr_b = await asyncio.wait_for(process.communicate(), self.timeout)
    except TimeoutError as e:
        process.kill()
        await process.wait()
        msg = f"Command timed out after {self.timeout} s"
        raise CommandError(msg) from e
    except asyncio.CancelledError:
        process.kill()
        await process.wait()
        raise
    stdout = stdout_b.decode(errors="replace")
    stderr = stderr_b.decode(errors="replace")
    if process.returncode:
        msg = f"Command failed with exit code {process.returncode}"
        if stderr:
            msg = f"{msg}\n{stderr}"
        raise CommandError(msg)
    if stdout:
        await ctx.print(f"```\n{stdout.rstrip()}\n```")
    if stderr:
        await ctx.print(f"**stderr:**\n```\n{stderr.rstrip()}\n```")

get_completer

get_completer() -> PathCompleter

Get path completer for executables.

Source code in src/slashed/builtin/system.py
def get_completer(self) -> PathCompleter:
    """Get path completer for executables."""
    return PathCompleter(directories=True, files=True)

:fa-brands-github: Show source on GitHub