Skip to content

Subprocess

rn_forge.commons.runtime.subprocess

Subprocess execution with structured result capture.

Typical usage::

from rn_forge.commons.runtime.subprocess import Process

result = Process.execute("list-files", "ls", "-la", "/tmp")
if result.succeeded:
    print(result.stdout)

Process(name, args, return_code, stdout, stderr, kwargs=dict[str, Any](), error=None, completed_process=None) dataclass

Bases: DataclassMixin

Immutable record of a subprocess execution.

Construct via :meth:execute or the named shortcuts (:meth:python, :meth:mvn, :meth:npm, :meth:az, :meth:pwsh). Instances are frozen dataclasses, so all fields are set at construction time.

Fields kwargs, error, and completed_process are excluded from serialisation (they carry metadata={"exclude": True}).

Attributes:

Name Type Description
name str

Human-readable label for the process used in log messages and :exc:~rn_forge.commons.AppException messages.

args list[str]

The exact argument list forwarded to :func:subprocess.run.

return_code int

Exit code of the process (-1 when execution raised an exception before the process could return).

stdout str | None

Decoded standard output, or None when capture_output was False.

stderr str | None

Decoded standard error, or None when capture_output was False.

kwargs dict[str, Any]

Extra keyword arguments that were passed to :func:subprocess.run. Excluded from serialisation.

error Exception | None

The exception raised during execution, if any. Excluded from serialisation.

completed_process CompletedProcess[Any] | None

The raw :class:subprocess.CompletedProcess result. Excluded from serialisation and equality comparison.

Example::

result = Process.execute("ping", "ping", "-c", "1", "localhost")
assert result.succeeded
assert "localhost" in (result.stdout or "")

Process.python("scripts/build_report.py", "--date", "2026-04-23")

succeeded property

Whether the process exited successfully.

Returns:

Type Description
bool

True when :attr:return_code is zero, False otherwise.

__repr__()

Return an unambiguous ClassName(field=value, ...) representation.

Excluded fields (metadata={"exclude": True}) are omitted. Falls back to :func:object.__repr__ when the class is not a dataclass.

Returns:

Type Description
str

A string of the form ClassName(field1=value1, field2=value2).

__str__()

Return a JSON string representation of this instance.

Equivalent to calling :meth:to_json. Excluded fields are omitted.

Returns:

Type Description
str

A compact JSON string (no indentation).

as_dict(*, exclude_hidden=True)

Convert this dataclass instance to a plain dict.

Parameters:

Name Type Description Default
exclude_hidden bool

When True (default), fields decorated with metadata={"exclude": True} are omitted from the result, recursively throughout nested dataclasses. Pass False to include every field.

True

Returns:

Type Description
dict[str, Any]

A dict mapping field names to their current values. Nested

dict[str, Any]

dataclasses are recursively converted, respecting exclude

dict[str, Any]

metadata at every level.

Raises:

Type Description
TypeError

If the subclass was not decorated with @dataclasses.dataclass.

az(cmd, *args, **kwargs) classmethod

Run an Azure CLI (az) command.

Parameters:

Name Type Description Default
cmd str

The az subcommand string (e.g. "login", "account list").

required
*args str

Additional arguments appended after cmd.

()
**kwargs Any

Forwarded to :meth:execute. Pass name=... to override the default process label.

{}

Returns:

Name Type Description
A Self

class:Process result from :meth:execute.

Raises:

Type Description
AppException

If cmd is empty or az is not on PATH.

execute(name, *args, fail_on_error=True, capture_output=True, **kwargs) classmethod

Run a subprocess and return an immutable :class:Process result.

Parameters:

Name Type Description Default
name str

Human-readable label for this process (used in log messages and exception messages).

required
*args str

Command and arguments forwarded to :func:subprocess.run. The first element must be the executable.

()
fail_on_error bool

When True (default), raise :exc:~rn_forge.commons.AppException if the process exits with a non-zero return code.

True
capture_output bool

When True (default), capture stdout and stderr as UTF-8 strings (with "ignore" error handling).

True
**kwargs Any

Additional keyword arguments forwarded verbatim to :func:subprocess.run (e.g. cwd, env, timeout).

{}

Returns:

Name Type Description
A Self

class:Process instance populated with the exit code, stdout,

Self

stderr, and the raw :class:subprocess.CompletedProcess.

Example::

result = Process.execute(
    "list-files",
    "ls",
    "-la",
    cwd=".",
    fail_on_error=False,
)

Raises:

Type Description
AppException

If args is empty or contains an empty string.

AppException

If fail_on_error=True and the process exits with a non-zero return code.

from_dict(data) classmethod

Create an instance from a dict, recursively rebuilding nested dataclasses.

Only keys that match declared dataclass field names are passed to the constructor. This makes from_dict tolerant of extra data (e.g. when loading from a config file that has fields added in a newer schema version). Nested dataclass-typed fields are reconstructed recursively for common container annotations, via :mod:dacite.

Note a nested dataclass field's own overridden from_dict (if any) is not called — dacite structures nested dataclasses itself.

Parameters:

Name Type Description Default
data dict[str, Any]

A dict whose keys correspond to dataclass field names. Unrecognised keys are silently ignored, or rejected when the class's __dacite_config__ sets strict.

required

Returns:

Type Description
Self

A new instance of this class populated with matching field values.

Raises:

Type Description
AppException

A value does not match its field's declared type, a required field is absent, or an enum-typed field names a member the enum does not define. Under strict, also a key that names no field, at any nesting level; the message lists every such key by its dotted path (repository.archtype).

TypeError

If the subclass was not decorated with @dataclasses.dataclass.

from_json(text) classmethod

Create an instance from a JSON string.

Delegates to :meth:from_dict after parsing, so unknown keys are ignored.

Parameters:

Name Type Description Default
text str

A JSON string representing a dict of field values.

required

Returns:

Type Description
Self

A new instance populated from the parsed JSON.

Raises:

Type Description
JSONDecodeError

If text is not valid JSON.

from_yaml(text) classmethod

Create an instance from a YAML string.

Delegates to :meth:from_dict after parsing, so unknown keys are ignored.

Parameters:

Name Type Description Default
text str

A YAML string representing a mapping of field values.

required

Returns:

Type Description
Self

A new instance populated from the parsed YAML.

Raises:

Type Description
YAMLError

If text is not valid YAML.

mvn(pom, *args, **kwargs) classmethod

Run a Maven command against a POM file.

Parameters:

Name Type Description Default
pom str | Path

Path to the pom.xml file.

required
*args str

Maven goals and arguments (e.g. "clean", "install").

()
**kwargs Any

Forwarded to :meth:execute. Pass name=... to override the default process label.

{}

Returns:

Name Type Description
A Self

class:Process result from :meth:execute.

Raises:

Type Description
AppException

If pom does not exist or mvn is not on PATH.

npm(project, *args, **kwargs) classmethod

Run an npm command in project directory.

Parameters:

Name Type Description Default
project str | Path

Path to the directory containing package.json.

required
*args str

npm arguments (e.g. "install", "run", "build").

()
**kwargs Any

Forwarded to :meth:execute. Pass name=... to override the default process label.

{}

Returns:

Name Type Description
A Self

class:Process result from :meth:execute.

Raises:

Type Description
AppException

If package.json is not found in project or npm is not on PATH.

pwsh(cmd_or_script, *args, mode='command', **kwargs) classmethod

Run a PowerShell (pwsh) command or script.

Parameters:

Name Type Description Default
cmd_or_script str | Path

A PowerShell command string or a path to a .ps1 script file.

required
*args str

Additional arguments appended to the pwsh invocation.

()
mode str

"command" (default) executes cmd_or_script as an inline command (-Command). "file" treats it as a script path (-File).

'command'
**kwargs Any

Forwarded to :meth:execute. Pass name=... to override the default process label.

{}

Returns:

Name Type Description
A Self

class:Process result from :meth:execute.

Raises:

Type Description
AppException

If cmd_or_script is empty, mode="file" is used and the script path does not exist, or pwsh is not on PATH.

python(file, *args, **kwargs) classmethod

Run a Python script using the active Python interpreter.

Parameters:

Name Type Description Default
file str | Path

Path to the .py script to execute.

required
*args str

Additional arguments passed to the script.

()
**kwargs Any

Forwarded to :meth:execute (e.g. cwd, timeout). Pass name=... to override the default process label.

{}

Returns:

Name Type Description
A Self

class:Process result from :meth:execute.

Example::

Process.python("scripts/build_report.py", "--date", "2026-04-23")

Raises:

Type Description
AppException

If file does not exist.

to_json(*, indent=None, **kwargs)

Serialise this instance to a JSON string.

Fields excluded via metadata={"exclude": True} are omitted.

Parameters:

Name Type Description Default
indent str | int | None

Indentation level passed to :func:json.dumps. None produces compact output.

None
**kwargs Any

Additional keyword arguments forwarded to :func:json.dumps.

{}

Returns:

Type Description
str

A JSON string representation of this instance.

to_yaml(**kwargs)

Serialise this instance to a YAML string.

Fields excluded via metadata={"exclude": True} are omitted.

Parameters:

Name Type Description Default
**kwargs Any

Additional keyword arguments forwarded to :meth:~rn_forge.commons.fs.documents.YamlUtils.serialize (e.g. sort_keys, default_flow_style).

{}

Returns:

Type Description
str

A YAML string representation of this instance.