proclet 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- proclet/__init__.py +38 -0
- proclet/_io.py +24 -0
- proclet/_platform.py +97 -0
- proclet/_streams.py +76 -0
- proclet/bind.py +193 -0
- proclet/env.py +106 -0
- proclet/errors.py +61 -0
- proclet/process.py +1440 -0
- proclet/py.typed +0 -0
- proclet/redirect.py +31 -0
- proclet-0.1.0.dist-info/METADATA +495 -0
- proclet-0.1.0.dist-info/RECORD +14 -0
- proclet-0.1.0.dist-info/WHEEL +4 -0
- proclet-0.1.0.dist-info/licenses/LICENSE +202 -0
proclet/__init__.py
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
"""Fluent, typed subprocess wrapper with sync and async execution and pipelines."""
|
|
2
|
+
|
|
3
|
+
from proclet.bind import Bind
|
|
4
|
+
from proclet.env import EnvCmd, PathCmd
|
|
5
|
+
from proclet.errors import CommandNotFound, ErrorReturnCode, TimeoutException
|
|
6
|
+
from proclet.process import (
|
|
7
|
+
AsyncProcess,
|
|
8
|
+
Command,
|
|
9
|
+
Process,
|
|
10
|
+
ProcessObserver,
|
|
11
|
+
SyncProcess,
|
|
12
|
+
)
|
|
13
|
+
from proclet.redirect import (
|
|
14
|
+
AsyncRedirectIn,
|
|
15
|
+
RedirectIn,
|
|
16
|
+
RedirectOut,
|
|
17
|
+
SyncRedirectIn,
|
|
18
|
+
strip_redirect,
|
|
19
|
+
)
|
|
20
|
+
|
|
21
|
+
__all__ = [
|
|
22
|
+
"AsyncProcess",
|
|
23
|
+
"AsyncRedirectIn",
|
|
24
|
+
"Bind",
|
|
25
|
+
"Command",
|
|
26
|
+
"CommandNotFound",
|
|
27
|
+
"EnvCmd",
|
|
28
|
+
"ErrorReturnCode",
|
|
29
|
+
"PathCmd",
|
|
30
|
+
"Process",
|
|
31
|
+
"ProcessObserver",
|
|
32
|
+
"RedirectIn",
|
|
33
|
+
"RedirectOut",
|
|
34
|
+
"SyncProcess",
|
|
35
|
+
"SyncRedirectIn",
|
|
36
|
+
"TimeoutException",
|
|
37
|
+
"strip_redirect",
|
|
38
|
+
]
|
proclet/_io.py
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
"""Private I/O helpers shared by the process module."""
|
|
2
|
+
|
|
3
|
+
from collections.abc import Sequence
|
|
4
|
+
from contextlib import suppress
|
|
5
|
+
from typing import Protocol
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class Closeable(Protocol):
|
|
9
|
+
"""Protocol for objects that support closing."""
|
|
10
|
+
|
|
11
|
+
def close(self) -> None:
|
|
12
|
+
"""Close the object."""
|
|
13
|
+
...
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def close(files: Sequence[Closeable]) -> None:
|
|
17
|
+
"""Close file handles, ignoring any `OSError`.
|
|
18
|
+
|
|
19
|
+
Args:
|
|
20
|
+
files: file handles to close.
|
|
21
|
+
"""
|
|
22
|
+
for file in files:
|
|
23
|
+
with suppress(OSError):
|
|
24
|
+
file.close()
|
proclet/_platform.py
ADDED
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
"""Platform-specific helpers for spawn options (priority, POSIX-only checks)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import ctypes
|
|
6
|
+
import os
|
|
7
|
+
import platform
|
|
8
|
+
import subprocess
|
|
9
|
+
import sys
|
|
10
|
+
from collections.abc import Callable, Mapping
|
|
11
|
+
from contextlib import suppress
|
|
12
|
+
from types import MappingProxyType
|
|
13
|
+
from typing import Final
|
|
14
|
+
|
|
15
|
+
# `ioprio_set` syscall numbers by machine; unknown machines skip the IO class.
|
|
16
|
+
_IOPRIO_SYSCALL: Final[Mapping[str, int]] = MappingProxyType(
|
|
17
|
+
{"x86_64": 251, "aarch64": 30}
|
|
18
|
+
)
|
|
19
|
+
_IOPRIO_WHO_PROCESS: Final[int] = 1
|
|
20
|
+
_IOPRIO_CLASS_IDLE: Final[int] = 3
|
|
21
|
+
_IOPRIO_CLASS_SHIFT: Final[int] = 13
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def low_priority_hook(nice: int | None) -> Callable[[], None] | None:
|
|
25
|
+
"""Build the `preexec_fn` lowering CPU (and, on Linux, IO) priority of a child.
|
|
26
|
+
|
|
27
|
+
Everything the hook needs is resolved here, before the fork, so the hook
|
|
28
|
+
itself only makes plain syscalls. IO priority is best effort: it is
|
|
29
|
+
skipped off Linux and on unknown machines, and failures are ignored.
|
|
30
|
+
Windows has no `preexec_fn`; see `priority_creationflags` instead.
|
|
31
|
+
|
|
32
|
+
Args:
|
|
33
|
+
nice: niceness to apply, `None` for no change.
|
|
34
|
+
Returns:
|
|
35
|
+
the hook, or `None` when no priority change is requested or on Windows.
|
|
36
|
+
"""
|
|
37
|
+
if nice is None or sys.platform == "win32":
|
|
38
|
+
return None
|
|
39
|
+
|
|
40
|
+
syscall = None
|
|
41
|
+
number = (
|
|
42
|
+
_IOPRIO_SYSCALL.get(platform.machine()) if sys.platform == "linux" else None
|
|
43
|
+
)
|
|
44
|
+
if number is not None:
|
|
45
|
+
with suppress(OSError, AttributeError):
|
|
46
|
+
syscall = ctypes.CDLL(None, use_errno=True).syscall
|
|
47
|
+
|
|
48
|
+
def hook() -> None:
|
|
49
|
+
os.setpriority(os.PRIO_PROCESS, 0, nice)
|
|
50
|
+
if syscall is not None:
|
|
51
|
+
syscall(
|
|
52
|
+
number,
|
|
53
|
+
_IOPRIO_WHO_PROCESS,
|
|
54
|
+
0,
|
|
55
|
+
_IOPRIO_CLASS_IDLE << _IOPRIO_CLASS_SHIFT,
|
|
56
|
+
)
|
|
57
|
+
|
|
58
|
+
return hook
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def priority_creationflags(nice: int | None) -> int:
|
|
62
|
+
"""Map a niceness to the Windows priority class of a child.
|
|
63
|
+
|
|
64
|
+
Windows has no niceness, only a handful of priority classes, so the value
|
|
65
|
+
is bucketed: >= 15 idle, 1..14 below normal, 0 unchanged, -14..-1 above
|
|
66
|
+
normal, <= -15 high (never realtime).
|
|
67
|
+
|
|
68
|
+
Args:
|
|
69
|
+
nice: niceness to apply, `None` for no change.
|
|
70
|
+
Returns:
|
|
71
|
+
the `creationflags` to pass on spawn, `0` off Windows or for no change.
|
|
72
|
+
"""
|
|
73
|
+
if nice is None or nice == 0 or sys.platform != "win32":
|
|
74
|
+
return 0
|
|
75
|
+
if nice >= 15:
|
|
76
|
+
name = "IDLE_PRIORITY_CLASS"
|
|
77
|
+
elif nice > 0:
|
|
78
|
+
name = "BELOW_NORMAL_PRIORITY_CLASS"
|
|
79
|
+
elif nice > -15:
|
|
80
|
+
name = "ABOVE_NORMAL_PRIORITY_CLASS"
|
|
81
|
+
else:
|
|
82
|
+
name = "HIGH_PRIORITY_CLASS"
|
|
83
|
+
# Only defined on Windows.
|
|
84
|
+
return getattr(subprocess, name)
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def require_os(option: str, func: str) -> None:
|
|
88
|
+
"""Fail fast when the platform can't apply a POSIX-only spawn option.
|
|
89
|
+
|
|
90
|
+
Args:
|
|
91
|
+
option: name of the option being set, for the error message.
|
|
92
|
+
func: `os` function the option relies on, e.g. `setgroups`.
|
|
93
|
+
Raises:
|
|
94
|
+
ValueError: if `os` lacks `func` (e.g. on Windows).
|
|
95
|
+
"""
|
|
96
|
+
if not hasattr(os, func):
|
|
97
|
+
raise ValueError(f"'{option}' is only supported on POSIX platforms")
|
proclet/_streams.py
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
"""Helpers moving data between Python objects and process pipes."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
from io import IOBase, TextIOBase
|
|
7
|
+
from typing import Final
|
|
8
|
+
|
|
9
|
+
from proclet.redirect import RedirectOut
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def needs_forwarding(redirect: RedirectOut | None) -> bool:
|
|
13
|
+
"""Check if a redirect needs a forwarding thread or task."""
|
|
14
|
+
if redirect is None:
|
|
15
|
+
return False
|
|
16
|
+
if callable(redirect):
|
|
17
|
+
return True
|
|
18
|
+
if isinstance(redirect, IOBase):
|
|
19
|
+
# File objects (text or binary) without a real fd (e.g. StringIO) need forwarding
|
|
20
|
+
try:
|
|
21
|
+
redirect.fileno()
|
|
22
|
+
return False
|
|
23
|
+
except (OSError, AttributeError):
|
|
24
|
+
return True
|
|
25
|
+
return False
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
# Read size used to feed a file object without a real fd (e.g. StringIO) to stdin.
|
|
29
|
+
STDIN_CHUNK_SIZE: Final[int] = 64 * 1024
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def encode_input(data: bytes | str) -> bytes:
|
|
33
|
+
"""Encode stdin input, passing bytes through untouched."""
|
|
34
|
+
return data if isinstance(data, bytes) else data.encode()
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def dispatch_line(target: RedirectOut, line: bytes) -> None:
|
|
38
|
+
"""Hand one line of process output to a forwarded redirect target.
|
|
39
|
+
|
|
40
|
+
Callables and text streams get the line decoded (invalid bytes replaced);
|
|
41
|
+
binary streams without a real fd (e.g. BytesIO) get the raw bytes.
|
|
42
|
+
|
|
43
|
+
Args:
|
|
44
|
+
target: the redirect target, one that `needs_forwarding` accepted.
|
|
45
|
+
line: the raw line read from the process.
|
|
46
|
+
"""
|
|
47
|
+
if callable(target):
|
|
48
|
+
target(line.decode(errors="replace"))
|
|
49
|
+
elif isinstance(target, TextIOBase):
|
|
50
|
+
target.write(line.decode(errors="replace"))
|
|
51
|
+
elif isinstance(target, IOBase):
|
|
52
|
+
target.write(line)
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
async def read_line(stream: asyncio.StreamReader) -> bytes:
|
|
56
|
+
"""Read one line of any length, like the sync forwarder's `readline()`.
|
|
57
|
+
|
|
58
|
+
`StreamReader.readline()` raises once a line outgrows the stream's buffer
|
|
59
|
+
limit (64 KiB by default), which would stop the forwarding for good.
|
|
60
|
+
|
|
61
|
+
Args:
|
|
62
|
+
stream: the stream reader to read from.
|
|
63
|
+
Returns:
|
|
64
|
+
the line including its trailing newline, or `b""` at EOF.
|
|
65
|
+
"""
|
|
66
|
+
chunks: list[bytes] = []
|
|
67
|
+
while True:
|
|
68
|
+
try:
|
|
69
|
+
chunks.append(await stream.readuntil(b"\n"))
|
|
70
|
+
break
|
|
71
|
+
except asyncio.IncompleteReadError as err:
|
|
72
|
+
chunks.append(err.partial)
|
|
73
|
+
break
|
|
74
|
+
except asyncio.LimitOverrunError as err:
|
|
75
|
+
chunks.append(await stream.readexactly(err.consumed))
|
|
76
|
+
return b"".join(chunks)
|
proclet/bind.py
ADDED
|
@@ -0,0 +1,193 @@
|
|
|
1
|
+
"""Base class for typed wrappers around one binary."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Sequence
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
from typing import Self, overload
|
|
8
|
+
|
|
9
|
+
from proclet.process import Command, ProcessObserver
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class Bind:
|
|
13
|
+
"""Base class for typed wrappers around one binary.
|
|
14
|
+
|
|
15
|
+
A bind holds the context shared by every operation on its binary: env,
|
|
16
|
+
cwd, user, groups, niceness and observers. Subclasses call
|
|
17
|
+
`super().__init__("<binary>")`, may set default context with the setters
|
|
18
|
+
below, and expose operations
|
|
19
|
+
built with `_command()`, which returns a fresh `Command` each time: an
|
|
20
|
+
operation either returns that command for the caller to configure and
|
|
21
|
+
run, or runs it and returns a processed result. Per-operation settings
|
|
22
|
+
(args, redirects, timeout, exit codes) live on that command only, so they
|
|
23
|
+
never leak from one operation into the next.
|
|
24
|
+
"""
|
|
25
|
+
|
|
26
|
+
def __init__(
|
|
27
|
+
self, cmd_path: str | Path, search_path: Sequence[str] | None = None
|
|
28
|
+
) -> None:
|
|
29
|
+
"""Init bind.
|
|
30
|
+
|
|
31
|
+
Args:
|
|
32
|
+
cmd_path: command name or path, see `Command`.
|
|
33
|
+
search_path: directories to look the binary up in instead of `PATH`.
|
|
34
|
+
Raises:
|
|
35
|
+
CommandNotFound: if the command binary can't be found.
|
|
36
|
+
"""
|
|
37
|
+
self._template: Command = Command(cmd_path, search_path)
|
|
38
|
+
|
|
39
|
+
def _command(self, *args: str) -> Command:
|
|
40
|
+
"""Create a fresh command for one operation, carrying the bind's context.
|
|
41
|
+
|
|
42
|
+
Args:
|
|
43
|
+
*args: the operation's arguments.
|
|
44
|
+
Returns:
|
|
45
|
+
a new command, independent from the bind and from other operations.
|
|
46
|
+
"""
|
|
47
|
+
cmd = Command(self._template.binary_path()).copy(self._template)
|
|
48
|
+
return cmd.args(*args) if args else cmd
|
|
49
|
+
|
|
50
|
+
def add_observer(self, observer: ProcessObserver) -> Self:
|
|
51
|
+
"""Register an observer notified on the spawn and exit of every operation."""
|
|
52
|
+
self._template.add_observer(observer)
|
|
53
|
+
return self
|
|
54
|
+
|
|
55
|
+
@overload
|
|
56
|
+
def env(self) -> dict[str, str]: ...
|
|
57
|
+
|
|
58
|
+
@overload
|
|
59
|
+
def env(self, value: dict[str, str]) -> Self: ...
|
|
60
|
+
|
|
61
|
+
def env(self, value: dict[str, str] | None = None) -> dict[str, str] | Self:
|
|
62
|
+
"""Returns current env vars if no value is provided, otherwise set env vars.
|
|
63
|
+
|
|
64
|
+
See `Command.env()`: unset inherits the parent's environment.
|
|
65
|
+
|
|
66
|
+
Args:
|
|
67
|
+
value: env vars to set.
|
|
68
|
+
Returns:
|
|
69
|
+
current env vars if no value is provided or self for chaining.
|
|
70
|
+
"""
|
|
71
|
+
if value is None:
|
|
72
|
+
return self._template.env()
|
|
73
|
+
self._template.env(value)
|
|
74
|
+
return self
|
|
75
|
+
|
|
76
|
+
@overload
|
|
77
|
+
def cwd(self) -> Path: ...
|
|
78
|
+
|
|
79
|
+
@overload
|
|
80
|
+
def cwd(self, value: Path) -> Self: ...
|
|
81
|
+
|
|
82
|
+
def cwd(self, value: Path | None = None) -> Path | Self:
|
|
83
|
+
"""Returns current cwd if no value is provided, otherwise set cwd.
|
|
84
|
+
|
|
85
|
+
Args:
|
|
86
|
+
value: cwd to set.
|
|
87
|
+
Returns:
|
|
88
|
+
current cwd if no value is provided or self for chaining.
|
|
89
|
+
"""
|
|
90
|
+
if value is None:
|
|
91
|
+
return self._template.cwd()
|
|
92
|
+
self._template.cwd(value)
|
|
93
|
+
return self
|
|
94
|
+
|
|
95
|
+
@overload
|
|
96
|
+
def user(self) -> str | int | None: ...
|
|
97
|
+
|
|
98
|
+
@overload
|
|
99
|
+
def user(self, value: str | int) -> Self: ...
|
|
100
|
+
|
|
101
|
+
def user(self, value: str | int | None = None) -> str | int | None | Self:
|
|
102
|
+
"""Returns current user if no value is provided, otherwise set user.
|
|
103
|
+
|
|
104
|
+
See `Command.user()`: needs the privileges to switch user.
|
|
105
|
+
|
|
106
|
+
Args:
|
|
107
|
+
value: user (name or uid) to run the command as.
|
|
108
|
+
Returns:
|
|
109
|
+
current user if no value is provided or self for chaining.
|
|
110
|
+
Raises:
|
|
111
|
+
ValueError: if set on a non-POSIX platform.
|
|
112
|
+
"""
|
|
113
|
+
if value is None:
|
|
114
|
+
return self._template.user()
|
|
115
|
+
self._template.user(value)
|
|
116
|
+
return self
|
|
117
|
+
|
|
118
|
+
@overload
|
|
119
|
+
def group(self) -> str | int | None: ...
|
|
120
|
+
|
|
121
|
+
@overload
|
|
122
|
+
def group(self, value: str | int) -> Self: ...
|
|
123
|
+
|
|
124
|
+
def group(self, value: str | int | None = None) -> str | int | None | Self:
|
|
125
|
+
"""Returns current group if no value is provided, otherwise set group.
|
|
126
|
+
|
|
127
|
+
See `Command.group()`.
|
|
128
|
+
|
|
129
|
+
Args:
|
|
130
|
+
value: group (name or gid) to run the command as.
|
|
131
|
+
Returns:
|
|
132
|
+
current group if no value is provided or self for chaining.
|
|
133
|
+
Raises:
|
|
134
|
+
ValueError: if set on a non-POSIX platform.
|
|
135
|
+
"""
|
|
136
|
+
if value is None:
|
|
137
|
+
return self._template.group()
|
|
138
|
+
self._template.group(value)
|
|
139
|
+
return self
|
|
140
|
+
|
|
141
|
+
@overload
|
|
142
|
+
def extra_groups(self) -> list[str | int] | None: ...
|
|
143
|
+
|
|
144
|
+
@overload
|
|
145
|
+
def extra_groups(self, value: Sequence[str | int]) -> Self: ...
|
|
146
|
+
|
|
147
|
+
def extra_groups(
|
|
148
|
+
self, value: Sequence[str | int] | None = None
|
|
149
|
+
) -> list[str | int] | None | Self:
|
|
150
|
+
"""Returns current supplementary groups if no value is provided, otherwise set them.
|
|
151
|
+
|
|
152
|
+
See `Command.extra_groups()`: unset keeps the parent's groups.
|
|
153
|
+
|
|
154
|
+
Args:
|
|
155
|
+
value: supplementary groups (names or gids); empty drops them all.
|
|
156
|
+
Returns:
|
|
157
|
+
current supplementary groups if no value is provided or self for chaining.
|
|
158
|
+
Raises:
|
|
159
|
+
ValueError: if set on a non-POSIX platform.
|
|
160
|
+
"""
|
|
161
|
+
if value is None:
|
|
162
|
+
return self._template.extra_groups()
|
|
163
|
+
self._template.extra_groups(value)
|
|
164
|
+
return self
|
|
165
|
+
|
|
166
|
+
@overload
|
|
167
|
+
def nice(self) -> int | None: ...
|
|
168
|
+
|
|
169
|
+
@overload
|
|
170
|
+
def nice(self, value: int) -> Self: ...
|
|
171
|
+
|
|
172
|
+
def nice(self, value: int | None = None) -> int | None | Self:
|
|
173
|
+
"""Returns current niceness if no value is provided, otherwise set it.
|
|
174
|
+
|
|
175
|
+
See `Command.nice()` for the per-platform behaviour.
|
|
176
|
+
|
|
177
|
+
Args:
|
|
178
|
+
value: niceness to run the command with, e.g. 19 for the lowest priority.
|
|
179
|
+
Returns:
|
|
180
|
+
current niceness if no value is provided or self for chaining.
|
|
181
|
+
"""
|
|
182
|
+
if value is None:
|
|
183
|
+
return self._template.nice()
|
|
184
|
+
self._template.nice(value)
|
|
185
|
+
return self
|
|
186
|
+
|
|
187
|
+
def binary_path(self) -> Path:
|
|
188
|
+
"""Get the binary this bind runs.
|
|
189
|
+
|
|
190
|
+
Returns:
|
|
191
|
+
the binary's path, as resolved at construction.
|
|
192
|
+
"""
|
|
193
|
+
return self._template.binary_path()
|
proclet/env.py
ADDED
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
"""Builders for the environment passed to a command."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import os
|
|
6
|
+
from collections.abc import Callable
|
|
7
|
+
from typing import Self
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class EnvCmd:
|
|
11
|
+
"""Builder for the env vars passed to `Command.env()`."""
|
|
12
|
+
|
|
13
|
+
def __init__(self) -> None:
|
|
14
|
+
"""Init an empty env command, same as `empty()`."""
|
|
15
|
+
self.__build: dict[str, str] = {}
|
|
16
|
+
|
|
17
|
+
@staticmethod
|
|
18
|
+
def empty() -> EnvCmd:
|
|
19
|
+
"""Create an empty env command."""
|
|
20
|
+
return EnvCmd()
|
|
21
|
+
|
|
22
|
+
@staticmethod
|
|
23
|
+
def inherit(predicate: Callable[[str, str], bool] | None = None) -> EnvCmd:
|
|
24
|
+
"""Create an env command that inherits env vars from the current process.
|
|
25
|
+
|
|
26
|
+
Args:
|
|
27
|
+
predicate: keeps only the `(key, value)` pairs it returns True for;
|
|
28
|
+
every variable is kept when omitted.
|
|
29
|
+
Returns:
|
|
30
|
+
the env command.
|
|
31
|
+
"""
|
|
32
|
+
env = EnvCmd()
|
|
33
|
+
if predicate:
|
|
34
|
+
env.__build = {
|
|
35
|
+
key: value for key, value in os.environ.items() if predicate(key, value)
|
|
36
|
+
}
|
|
37
|
+
else:
|
|
38
|
+
env.__build = os.environ.copy()
|
|
39
|
+
return env
|
|
40
|
+
|
|
41
|
+
def add(self, env_vars: dict[str, str]) -> Self:
|
|
42
|
+
"""Add env vars, overriding any already set under the same key.
|
|
43
|
+
|
|
44
|
+
Args:
|
|
45
|
+
env_vars: env vars to add.
|
|
46
|
+
Returns:
|
|
47
|
+
self for chaining.
|
|
48
|
+
"""
|
|
49
|
+
self.__build.update(env_vars)
|
|
50
|
+
return self
|
|
51
|
+
|
|
52
|
+
def build(self) -> dict[str, str]:
|
|
53
|
+
"""Build the env vars, for `Command.env()`.
|
|
54
|
+
|
|
55
|
+
Returns:
|
|
56
|
+
a copy of the env vars built so far.
|
|
57
|
+
"""
|
|
58
|
+
return self.__build.copy()
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
class PathCmd:
|
|
62
|
+
"""Builder for a `PATH` env var value."""
|
|
63
|
+
|
|
64
|
+
def __init__(self) -> None:
|
|
65
|
+
"""Init an empty path command, same as `empty()`."""
|
|
66
|
+
self.__build: list[str] = []
|
|
67
|
+
|
|
68
|
+
@staticmethod
|
|
69
|
+
def empty() -> PathCmd:
|
|
70
|
+
"""Create an empty path command."""
|
|
71
|
+
return PathCmd()
|
|
72
|
+
|
|
73
|
+
@staticmethod
|
|
74
|
+
def inherit() -> PathCmd:
|
|
75
|
+
"""Create a path command that inherits `PATH` from the current process.
|
|
76
|
+
|
|
77
|
+
Empty entries are dropped, since a lookup would treat them as the
|
|
78
|
+
current directory.
|
|
79
|
+
|
|
80
|
+
Returns:
|
|
81
|
+
the path command.
|
|
82
|
+
"""
|
|
83
|
+
path = PathCmd()
|
|
84
|
+
path.__build = [
|
|
85
|
+
entry for entry in os.environ.get("PATH", "").split(os.pathsep) if entry
|
|
86
|
+
]
|
|
87
|
+
return path
|
|
88
|
+
|
|
89
|
+
def add(self, value: str) -> Self:
|
|
90
|
+
"""Prepend a directory, so it is searched before those already added.
|
|
91
|
+
|
|
92
|
+
Args:
|
|
93
|
+
value: directory to prepend.
|
|
94
|
+
Returns:
|
|
95
|
+
self for chaining.
|
|
96
|
+
"""
|
|
97
|
+
self.__build.insert(0, value)
|
|
98
|
+
return self
|
|
99
|
+
|
|
100
|
+
def build(self) -> str:
|
|
101
|
+
"""Build the `PATH` value.
|
|
102
|
+
|
|
103
|
+
Returns:
|
|
104
|
+
the `PATH` value, entries joined with `os.pathsep`.
|
|
105
|
+
"""
|
|
106
|
+
return os.pathsep.join(self.__build)
|
proclet/errors.py
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
"""Exceptions raised when running commands."""
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
class CommandNotFound(Exception):
|
|
5
|
+
"""Raised when a command binary is not found.
|
|
6
|
+
|
|
7
|
+
Raised by `Command(...)` for a name missing from the search path, or at
|
|
8
|
+
spawn time for a `Path` (or a binary removed since construction).
|
|
9
|
+
|
|
10
|
+
Attributes:
|
|
11
|
+
command: the name or path that couldn't be found.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
def __init__(self, command: str) -> None:
|
|
15
|
+
"""Init exception.
|
|
16
|
+
|
|
17
|
+
Args:
|
|
18
|
+
command: the name or path that couldn't be found.
|
|
19
|
+
"""
|
|
20
|
+
super().__init__(f"Command not found: {command}")
|
|
21
|
+
self.command: str = command
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class ErrorReturnCode(Exception):
|
|
25
|
+
"""Raised when a command exits with a code outside its `ok_exit_codes`.
|
|
26
|
+
|
|
27
|
+
Attributes:
|
|
28
|
+
cmd: the command line, binary path followed by its arguments.
|
|
29
|
+
exit_code: the process' exit code (negative signal number if killed).
|
|
30
|
+
"""
|
|
31
|
+
|
|
32
|
+
def __init__(self, cmd: str, exit_code: int) -> None:
|
|
33
|
+
"""Init exception.
|
|
34
|
+
|
|
35
|
+
Args:
|
|
36
|
+
cmd: the command line, binary path followed by its arguments.
|
|
37
|
+
exit_code: the process' exit code.
|
|
38
|
+
"""
|
|
39
|
+
super().__init__(f"Command '{cmd}' returned exit code {exit_code}")
|
|
40
|
+
self.cmd: str = cmd
|
|
41
|
+
self.exit_code: int = exit_code
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
class TimeoutException(Exception):
|
|
45
|
+
"""Raised when a command outlives its `timeout()`; the process is terminated.
|
|
46
|
+
|
|
47
|
+
Attributes:
|
|
48
|
+
cmd: the command line, binary path followed by its arguments.
|
|
49
|
+
timeout: the timeout that elapsed, in seconds.
|
|
50
|
+
"""
|
|
51
|
+
|
|
52
|
+
def __init__(self, cmd: str, timeout: float) -> None:
|
|
53
|
+
"""Init exception.
|
|
54
|
+
|
|
55
|
+
Args:
|
|
56
|
+
cmd: the command line, binary path followed by its arguments.
|
|
57
|
+
timeout: the timeout that elapsed, in seconds.
|
|
58
|
+
"""
|
|
59
|
+
super().__init__(f"Command '{cmd}' timed out after {timeout} seconds")
|
|
60
|
+
self.cmd: str = cmd
|
|
61
|
+
self.timeout: float = timeout
|