Skip to content

Runner

invoke_tasklib.runner

Helpers to build and run the commands of the tasks.

invoke_tasklib.runner.ARGS_HELP module-attribute

ARGS_HELP = 'Extra arguments for the tool, as one string, e.g. "-k foo -x".'

Help of the --args option of the tasks.

invoke_tasklib.runner.PATHS_HELP module-attribute

PATHS_HELP = "Files or directories to run on, as one string, instead of the default (globs and ~ are passed as they are)."

Help of the --paths option of the tasks.

invoke_tasklib.runner.TOOL_HELP module-attribute

TOOL_HELP = {'args': ARGS_HELP, 'paths': PATHS_HELP}

The help of a task with the args and paths options.

invoke_tasklib.runner.build_command

build_command(
    words: Sequence[str],
    *,
    args: str | None = None,
    paths: str | None = None,
    default_paths: Sequence[str] = (),
    args_option: str = "--args",
) -> list[str]

Build a command from its words and the options of a task.

Parameters:

Name Type Description Default
words Sequence[str]

The program and its fixed arguments, e.g. ["ruff", "check"]. Nothing is quoted or split: a word is an argument of the program.

required
args str | None

Extra arguments of the user, as one string that is split like a shell does, e.g. "-k foo -x". They come after the fixed arguments.

None
paths str | None

Paths of the user, as one string that is split like a shell does. They replace default_paths. A glob (*) or ~ is passed as it is: it is up to the tool to expand a glob, and ~ is never expanded.

None
default_paths Sequence[str]

The paths used when paths is not set.

()
args_option str

The name of the option that args comes from, used in the error message (for a task that has more than one set of arguments, e.g. "--pyright-args").

'--args'

Returns:

Type Description
list[str]

The words, the split args and the paths. run quotes

list[str]

them, so the shell does not expand a glob, ~ or $VAR.

Raises:

Type Description
Exit

If args or paths cannot be split (for example an unclosed quote).

Example usage:

>>> from invoke_tasklib.runner import build_command
>>> build_command(["ruff", "check"], default_paths=["."])
['ruff', 'check', '.']
>>> build_command(["ruff"], args="-x", paths="src")
['ruff', '-x', 'src']
>>> build_command(["ruff"], paths="*.py")
['ruff', '*.py']

invoke_tasklib.runner.capture

capture(
    c: Context,
    command: Sequence[str],
    *,
    warn: bool = False,
    check: bool = True,
) -> Result

Run a command whose output the caller reads.

It is run with the options that a command read by the code needs: the output is hidden (hide=True) and the command is not echoed (echo=False), and no pty is used (pty=False), so that stderr is not merged into stdout and a warning of the tool is never read as data.

Parameters:

Name Type Description Default
c Context

The invoke context.

required
command Sequence[str]

The command to run, as a list of words, see run.

required
warn bool

If True, a command that fails does not raise: look at result.ok.

False
check bool

If False, do not check that the program is available, see run.

True

Returns:

Type Description
Result

The result of c.run, with the standard output in

Result

stdout.

Raises:

Type Description
TypeError

If command is a string: pass the words.

Exit

If check is True and the program of the command is not found.

UnexpectedExit

If the command fails and warn is False.

Example usage:

>>> from invoke.config import Config
>>> from invoke.context import MockContext
>>> from invoke_tasklib.runner import capture
>>> c = MockContext(config=Config(), run=True)
>>> _ = capture(c, ["ls"])
>>> c.run.call_args.kwargs["pty"]
False

invoke_tasklib.runner.in_ci

in_ci() -> bool

Tell whether the CI environment variable turns CI mode on.

Any value is accepted except an empty string, 0 and false (case-insensitive), so CI=false does not count as CI. Most CI services set CI=true, GitHub Actions included.

Returns:

Type Description
bool

True if CI is set to a value other than "", "0"

bool

and "false".

Example usage:

>>> import os
>>> from unittest.mock import patch
>>> from invoke_tasklib.runner import in_ci
>>> with patch.dict(os.environ, {"CI": "true"}):
...     in_ci()
True
>>> with patch.dict(os.environ, {"CI": "false"}):
...     in_ci()
False

invoke_tasklib.runner.in_github_actions

in_github_actions() -> bool

Tell whether the code runs in GitHub Actions.

Returns:

Type Description
bool

True if GITHUB_ACTIONS is exactly "true", the value

bool

that GitHub Actions sets.

Example usage:

>>> import os
>>> from unittest.mock import patch
>>> from invoke_tasklib.runner import in_github_actions
>>> with patch.dict(os.environ, {"GITHUB_ACTIONS": "true"}):
...     in_github_actions()
True
>>> with patch.dict(os.environ, {"GITHUB_ACTIONS": "false"}):
...     in_github_actions()
False

invoke_tasklib.runner.python_executable

python_executable() -> str

Return the path of the running Python interpreter.

Tasks that run Python code or a Python module use this interpreter instead of the python found on the PATH: the interpreter running Invoke is the one that has the project installed, and it works outside an activated virtual environment.

Returns:

Type Description
str

The path of sys.executable, as it is: run quotes it

str

with the other words of the command.

Example usage:

>>> import sys
>>> from invoke_tasklib.runner import python_executable
>>> python_executable() == sys.executable
True

invoke_tasklib.runner.run

run(
    c: Context,
    command: Sequence[str],
    *,
    check: bool = True,
    **kwargs: Any,
) -> Result

Run a command, echoing it and using a pty only on a terminal.

The program of the command must be on the PATH or in the directory of the running interpreter, see check_program. The command runs with tool_path() as its PATH, so it finds the programs of the virtual environment without an activation. Pass check=False to skip that check when the caller knows better, for example for a command that is defined by a shell function or alias.

All the tasks run their commands through this helper so that they behave alike:

  • the command line is echoed (echo=True) so that the user sees what is run, unless echo is passed explicitly;
  • a pseudo-terminal is used (pty=True) only if sys.stdout is a terminal or run.pty is set in the Invoke config. A pty keeps the colors of the tools but merges stderr into stdout and is not available everywhere (for example Windows or some CI sandboxes);
  • the PATH starts with the directory of the running interpreter (see tool_path). An env passed by the caller is added to it, and can set PATH itself.

Parameters:

Name Type Description Default
c Context

The invoke context.

required
command Sequence[str]

The command to run, as a list of words: each one is quoted for the shell, so a space, ;, *, ~ or $VAR reaches the program unchanged.

required
check bool

If False, do not check that the program is available.

True
**kwargs Any

Additional keyword arguments passed to c.run. They take precedence over the defaults of this helper.

{}

Returns:

Type Description
Result

The result of c.run.

Raises:

Type Description
TypeError

If command is a string: pass the words.

Exit

If check is True and the program of the command is not found.

Example usage:

>>> from invoke.config import Config
>>> from invoke.context import MockContext
>>> from invoke_tasklib.runner import run
>>> c = MockContext(config=Config(), run=True)
>>> _ = run(c, ["ls"])
>>> c.run.call_args.kwargs["echo"]
True
>>> _ = run(c, ["ls", "a b"])
>>> c.run.call_args.args
("ls 'a b'",)

invoke_tasklib.runner.split_args

split_args(value: str | None, option: str) -> list[str]

Split the value of an option like a shell does.

Parameters:

Name Type Description Default
value str | None

The value, or None if the option is not set.

required
option str

The name of the option, used in the error message.

required

Returns:

Type Description
list[str]

The words of the value (empty if it is not set).

Raises:

Type Description
Exit

If the value cannot be split, for example because of an unclosed quote.

Example usage:

>>> from invoke_tasklib.runner import split_args
>>> split_args('-k "a b" -x', "--args")
['-k', 'a b', '-x']
>>> split_args(None, "--args")
[]