Runner API Reference¶
Auto-generated API documentation for the runner module.
runner
¶
Structured subprocess execution — zero dependencies, stdlib only, Python 3.10+.
Part of zerodep: https://github.com/Oaklight/zerodep Copyright (c) 2026 Peng Ding. MIT License.
Run external commands with controlled execution: timeouts with graceful kill escalation, streaming output, environment isolation, and cross-platform support. Designed as a building block (Layer 1) for higher-level execution frameworks.
Quick start::
from runner import run
result = run("echo hello world")
print(result.stdout) # "hello world
" print(result.returncode) # 0 print(result.duration) # 0.003 (seconds)
Streaming output::
from runner import stream
with stream(["make", "build"]) as proc:
for line in proc.iter_lines():
print(f"[build] {line}", end="")
Async execution::
import asyncio
from runner import run_async
result = asyncio.run(run_async("ls -la"))
Requires Python 3.10+.
RunnerError
¶
CommandNotFoundError
¶
Bases: RunnerError
Raised when the command binary cannot be located on PATH.
Attributes:
| Name | Type | Description |
|---|---|---|
name |
The command name that was not found. |
Source code in runner/runner.py
CommandFailedError
¶
Bases: RunnerError
Raised when a command exits with a disallowed return code.
Attributes:
| Name | Type | Description |
|---|---|---|
result |
The full RunResult including stdout, stderr, returncode, duration. |
Source code in runner/runner.py
CommandTimeoutError
¶
Bases: RunnerError
Raised when a command exceeds its timeout.
Attributes:
| Name | Type | Description |
|---|---|---|
command |
The command that timed out. |
|
timeout |
The timeout value in seconds. |
|
partial_stdout |
Any stdout captured before the timeout. |
|
partial_stderr |
Any stderr captured before the timeout. |
Source code in runner/runner.py
CommandBlockedError
¶
Bases: RunnerError
Raised when a command is rejected by allowlist/blocklist policy.
Attributes:
| Name | Type | Description |
|---|---|---|
command |
The rejected command name. |
|
reason |
Human-readable explanation. |
Source code in runner/runner.py
RunResult
dataclass
¶
Result of a completed command execution.
Attributes:
| Name | Type | Description |
|---|---|---|
command |
tuple[str, ...]
|
The command and arguments as a tuple. |
returncode |
int
|
Process exit code. |
stdout |
str
|
Captured standard output (decoded text). |
stderr |
str
|
Captured standard error (decoded text). |
duration |
float
|
Wall-clock execution time in seconds. |
pid |
int
|
Process ID of the executed command. |
Source code in runner/runner.py
StreamHandle
¶
Live handle to a running process for streaming output.
Returned by the :func:stream context manager. Provides iterators
over stdout and/or stderr lines and process control methods.
Lifecycle
- Create — the :func:
streamcontext manager starts the subprocess, optionally writes input to stdin, then yields this handle. At this point the handle owns the process. - Yield lines — the caller iterates via :meth:
iter_linesor :meth:iter_any. Lines are yielded as they arrive. - Cleanup — when the
withblock exits (normally or via exception), :meth:_cleanupis called automatically.
Process ownership
The handle takes exclusive ownership of the underlying
:class:subprocess.Popen object. Callers must not interact
with the Popen directly. The handle is responsible for
ensuring the process is terminated when the context exits.
Unconsumed output
If the caller does not fully consume stdout/stderr (e.g. breaks
out of the iterator early), the remaining pipe data is
discarded during cleanup. The process is still terminated
cleanly via :meth:_cleanup.
Cleanup semantics
:meth:_cleanup checks whether the process is still running
(via poll()). If so, it calls
:func:_terminate_with_escalation (SIGTERM, then SIGKILL after
kill_delay seconds). The returncode attribute is then
set from the process exit code. Cleanup is invoked by the
finally clause in :func:stream, so it always runs even
if the caller raises an exception.
Attributes:
| Name | Type | Description |
|---|---|---|
pid |
int
|
Process ID. |
Source code in runner/runner.py
898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 | |
returncode
property
¶
Exit code, available after iteration completes or process exits.
iter_lines(*, source='stdout')
¶
Iterate over lines from stdout or stderr.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source
|
str
|
|
'stdout'
|
Yields:
| Type | Description |
|---|---|
str
|
Lines of text (including trailing newline). |
Source code in runner/runner.py
iter_any()
¶
Iterate over interleaved lines from both stdout and stderr.
Yields:
| Type | Description |
|---|---|
str
|
Tuples of |
str
|
or |
Source code in runner/runner.py
AsyncStreamHandle
¶
Async live handle to a running process for streaming output.
Returned by the :func:stream_async async context manager.
Lifecycle
- Create — :func:
stream_asyncstarts the subprocess viaasyncio.create_subprocess_exec, optionally writes input to stdin, then yields this handle. The handle owns the process from this point. - Yield lines — the caller iterates via
:meth:
aiter_linesor :meth:aiter_any. Lines are yielded as they arrive from the async stream readers. - Cleanup — when the
async withblock exits (normally or via exception), :meth:_cleanupis awaited automatically.
Process ownership
The handle takes exclusive ownership of the underlying
asyncio.subprocess.Process. Callers must not interact with
the process object directly.
Unconsumed output
If the caller does not fully consume stdout/stderr (e.g. breaks
out of the async iterator early), remaining pipe data is
discarded during cleanup. The process is still terminated
cleanly via :meth:_cleanup.
Cleanup semantics
:meth:_cleanup checks proc.returncode. If None (the
process is still running), it awaits
:func:_async_terminate_with_escalation (SIGTERM, then SIGKILL
after kill_delay seconds). The returncode attribute is
then set. Cleanup is invoked by the finally clause in
:func:stream_async.
Attributes:
| Name | Type | Description |
|---|---|---|
pid |
int
|
Process ID. |
Source code in runner/runner.py
1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 | |
returncode
property
¶
Exit code, available after iteration completes or process exits.
aiter_lines(*, source='stdout')
async
¶
Iterate over lines from stdout or stderr.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source
|
str
|
|
'stdout'
|
Yields:
| Type | Description |
|---|---|
AsyncIterator[str]
|
Lines of text (including trailing newline). |
Source code in runner/runner.py
aiter_any()
async
¶
Iterate over interleaved lines from both stdout and stderr.
Yields:
| Type | Description |
|---|---|
AsyncIterator[tuple[str, str]]
|
Tuples of |
AsyncIterator[tuple[str, str]]
|
or |
Source code in runner/runner.py
run(cmd, *, input=None, cwd=None, env=None, env_extra=None, env_remove=None, timeout=DEFAULT_TIMEOUT, kill_delay=DEFAULT_KILL_DELAY, check=True, encoding=DEFAULT_ENCODING, on_stdout=None, on_stderr=None, allowed_commands=None, blocked_commands=None)
¶
Run a command synchronously and return the result.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cmd
|
str | Sequence[str]
|
Command as a string (auto-split) or sequence of arguments. |
required |
input
|
str | None
|
Text to send on stdin. |
None
|
cwd
|
str | Path | None
|
Working directory for the subprocess. |
None
|
env
|
dict[str, str] | None
|
Complete replacement environment (no inheritance). |
None
|
env_extra
|
dict[str, str] | None
|
Extra variables to merge into the inherited environment. |
None
|
env_remove
|
Sequence[str] | None
|
Variables to strip from the inherited environment. |
None
|
timeout
|
float | None
|
Maximum seconds to wait. None means no timeout. |
DEFAULT_TIMEOUT
|
kill_delay
|
float
|
Seconds to wait between SIGTERM and SIGKILL. |
DEFAULT_KILL_DELAY
|
check
|
bool
|
If True, raise CommandFailedError on non-zero exit. |
True
|
encoding
|
str
|
Text encoding for stdout/stderr. |
DEFAULT_ENCODING
|
on_stdout
|
Callable[[str], None] | None
|
Per-line callback for stdout (output is still captured). |
None
|
on_stderr
|
Callable[[str], None] | None
|
Per-line callback for stderr (output is still captured). |
None
|
allowed_commands
|
Sequence[str] | None
|
If set, only these command names are permitted. |
None
|
blocked_commands
|
Sequence[str] | None
|
If set, these command names are rejected. |
None
|
Returns:
| Type | Description |
|---|---|
RunResult
|
A RunResult with captured output, exit code, and timing. |
Raises:
| Type | Description |
|---|---|
CommandNotFoundError
|
If the command binary is not found. |
CommandFailedError
|
If check=True and the exit code is non-zero. |
CommandTimeoutError
|
If execution exceeds timeout. |
CommandBlockedError
|
If the command violates the policy. |
ValueError
|
If the command is empty. |
Source code in runner/runner.py
486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 | |
run_async(cmd, *, input=None, cwd=None, env=None, env_extra=None, env_remove=None, timeout=DEFAULT_TIMEOUT, kill_delay=DEFAULT_KILL_DELAY, check=True, encoding=DEFAULT_ENCODING, on_stdout=None, on_stderr=None, allowed_commands=None, blocked_commands=None)
async
¶
Run a command asynchronously and return the result.
Async counterpart of :func:run. Uses
asyncio.create_subprocess_exec internally.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cmd
|
str | Sequence[str]
|
Command as a string (auto-split) or sequence of arguments. |
required |
input
|
str | None
|
Text to send on stdin. |
None
|
cwd
|
str | Path | None
|
Working directory for the subprocess. |
None
|
env
|
dict[str, str] | None
|
Complete replacement environment (no inheritance). |
None
|
env_extra
|
dict[str, str] | None
|
Extra variables to merge into the inherited environment. |
None
|
env_remove
|
Sequence[str] | None
|
Variables to strip from the inherited environment. |
None
|
timeout
|
float | None
|
Maximum seconds to wait. None means no timeout. |
DEFAULT_TIMEOUT
|
kill_delay
|
float
|
Seconds to wait between SIGTERM and SIGKILL. |
DEFAULT_KILL_DELAY
|
check
|
bool
|
If True, raise CommandFailedError on non-zero exit. |
True
|
encoding
|
str
|
Text encoding for stdout/stderr. |
DEFAULT_ENCODING
|
on_stdout
|
Callable[[str], None] | None
|
Per-line callback for stdout (output is still captured). |
None
|
on_stderr
|
Callable[[str], None] | None
|
Per-line callback for stderr (output is still captured). |
None
|
allowed_commands
|
Sequence[str] | None
|
If set, only these command names are permitted. |
None
|
blocked_commands
|
Sequence[str] | None
|
If set, these command names are rejected. |
None
|
Returns:
| Type | Description |
|---|---|
RunResult
|
A RunResult with captured output, exit code, and timing. |
Raises:
| Type | Description |
|---|---|
CommandNotFoundError
|
If the command binary is not found. |
CommandFailedError
|
If check=True and the exit code is non-zero. |
CommandTimeoutError
|
If execution exceeds timeout. |
CommandBlockedError
|
If the command violates the policy. |
ValueError
|
If the command is empty. |
Source code in runner/runner.py
769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 | |
stream(cmd, *, input=None, cwd=None, env=None, env_extra=None, env_remove=None, timeout=None, kill_delay=DEFAULT_KILL_DELAY, encoding=DEFAULT_ENCODING, allowed_commands=None, blocked_commands=None)
¶
Context manager for streaming subprocess output.
Yields a :class:StreamHandle that provides line iterators over
stdout and stderr. The process is automatically cleaned up on
context exit.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cmd
|
str | Sequence[str]
|
Command as a string (auto-split) or sequence of arguments. |
required |
input
|
str | None
|
Text to send on stdin. |
None
|
cwd
|
str | Path | None
|
Working directory for the subprocess. |
None
|
env
|
dict[str, str] | None
|
Complete replacement environment (no inheritance). |
None
|
env_extra
|
dict[str, str] | None
|
Extra variables to merge into the inherited environment. |
None
|
env_remove
|
Sequence[str] | None
|
Variables to strip from the inherited environment. |
None
|
timeout
|
float | None
|
Maximum seconds for the process. None means no timeout. |
None
|
kill_delay
|
float
|
Seconds to wait between SIGTERM and SIGKILL. |
DEFAULT_KILL_DELAY
|
encoding
|
str
|
Text encoding for stdout/stderr. |
DEFAULT_ENCODING
|
allowed_commands
|
Sequence[str] | None
|
If set, only these command names are permitted. |
None
|
blocked_commands
|
Sequence[str] | None
|
If set, these command names are rejected. |
None
|
Yields:
| Type | Description |
|---|---|
StreamHandle
|
A StreamHandle for reading process output. |
Raises:
| Type | Description |
|---|---|
CommandNotFoundError
|
If the command binary is not found. |
CommandBlockedError
|
If the command violates the policy. |
ValueError
|
If the command is empty. |
Source code in runner/runner.py
1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 | |
stream_async(cmd, *, input=None, cwd=None, env=None, env_extra=None, env_remove=None, timeout=None, kill_delay=DEFAULT_KILL_DELAY, encoding=DEFAULT_ENCODING, allowed_commands=None, blocked_commands=None)
async
¶
Async context manager for streaming subprocess output.
Yields an :class:AsyncStreamHandle that provides async line
iterators over stdout and stderr. The process is automatically
cleaned up on context exit.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cmd
|
str | Sequence[str]
|
Command as a string (auto-split) or sequence of arguments. |
required |
input
|
str | None
|
Text to send on stdin. |
None
|
cwd
|
str | Path | None
|
Working directory for the subprocess. |
None
|
env
|
dict[str, str] | None
|
Complete replacement environment (no inheritance). |
None
|
env_extra
|
dict[str, str] | None
|
Extra variables to merge into the inherited environment. |
None
|
env_remove
|
Sequence[str] | None
|
Variables to strip from the inherited environment. |
None
|
timeout
|
float | None
|
Maximum seconds for the process. None means no timeout. |
None
|
kill_delay
|
float
|
Seconds to wait between SIGTERM and SIGKILL. |
DEFAULT_KILL_DELAY
|
encoding
|
str
|
Text encoding for stdout/stderr. |
DEFAULT_ENCODING
|
allowed_commands
|
Sequence[str] | None
|
If set, only these command names are permitted. |
None
|
blocked_commands
|
Sequence[str] | None
|
If set, these command names are rejected. |
None
|
Yields:
| Type | Description |
|---|---|
AsyncIterator[AsyncStreamHandle]
|
An AsyncStreamHandle for reading process output. |
Raises:
| Type | Description |
|---|---|
CommandNotFoundError
|
If the command binary is not found. |
CommandBlockedError
|
If the command violates the policy. |
ValueError
|
If the command is empty. |
Source code in runner/runner.py
1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 | |
shell_split(s)
¶
Split a shell command string into a list of arguments.
Uses :func:shlex.split with POSIX mode on Unix and non-POSIX on
Windows.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
s
|
str
|
Shell command string, e.g. |
required |
Returns:
| Type | Description |
|---|---|
list[str]
|
List of arguments. |
Raises:
| Type | Description |
|---|---|
ValueError
|
On unterminated quotes or other parse errors. |
Source code in runner/runner.py
shell_quote(*args)
¶
Quote arguments for safe shell interpolation.
On Unix, uses :func:shlex.quote. On Windows, uses cmd.exe-safe
quoting with double-quote escaping.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
*args
|
str
|
Individual arguments to quote. |
()
|
Returns:
| Type | Description |
|---|---|
str
|
Space-joined quoted string. |
Source code in runner/runner.py
which(name)
¶
Locate a command on the system PATH.
Cross-platform wrapper around :func:shutil.which.
Binary lookup order (Pattern 2 convention):
1. Exact path — if name is absolute, return it directly if it exists.
2. PATH search — delegates to :func:shutil.which, which walks
os.environ["PATH"] entries in order, respecting PATHEXT on
Windows.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Command name (e.g. |
required |
Returns:
| Type | Description |
|---|---|
str | None
|
Absolute path to the binary, or |