proclet 0.1.0__tar.gz

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-0.1.0/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
proclet-0.1.0/PKG-INFO ADDED
@@ -0,0 +1,495 @@
1
+ Metadata-Version: 2.4
2
+ Name: proclet
3
+ Version: 0.1.0
4
+ Summary: Fluent, typed subprocess wrapper with sync and async execution and pipelines.
5
+ Keywords: subprocess,process,pipeline,asyncio,shell
6
+ Author: Adrien Mannocci
7
+ Author-email: Adrien Mannocci <adrien.mannocci@gmail.com>
8
+ License-Expression: Apache-2.0
9
+ License-File: LICENSE
10
+ Classifier: Development Status :: 4 - Beta
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: Operating System :: Microsoft :: Windows
13
+ Classifier: Operating System :: POSIX
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3.12
16
+ Classifier: Programming Language :: Python :: 3.13
17
+ Classifier: Topic :: System :: Shells
18
+ Classifier: Typing :: Typed
19
+ Requires-Python: >=3.12
20
+ Project-URL: Repository, https://github.com/techcode-io/proclet
21
+ Project-URL: Documentation, https://github.com/techcode-io/proclet#readme
22
+ Project-URL: Tracker, https://github.com/techcode-io/proclet/issues
23
+ Description-Content-Type: text/markdown
24
+
25
+ <h1 align="center">Proclet</h1>
26
+
27
+ <p align="center">
28
+ <i align="center">Proclet is a fluent, typed wrapper around Python's subprocess, with matching sync and async APIs, binary-safe pipelines, privilege dropping and low-priority execution.</i>
29
+ </p>
30
+
31
+ <h4 align="center">
32
+ <a href="https://pypi.org/project/proclet/">
33
+ <img src="https://img.shields.io/pypi/v/proclet?style=flat-square" alt="pypi version" style="height: 20px;">
34
+ </a>
35
+ <a href="https://pypi.org/project/proclet/">
36
+ <img src="https://img.shields.io/pypi/pyversions/proclet?style=flat-square" alt="python versions" style="height: 20px;">
37
+ </a>
38
+ <a href="https://github.com/techcode-io/proclet/actions/workflows/ci.yml">
39
+ <img src="https://img.shields.io/github/actions/workflow/status/techcode-io/proclet/ci.yml?branch=main&label=ci&style=flat-square" alt="continuous integration" style="height: 20px;">
40
+ </a>
41
+ <a href="https://github.com/techcode-io/proclet/graphs/contributors">
42
+ <img src="https://img.shields.io/github/contributors-anon/techcode-io/proclet?color=yellow&style=flat-square" alt="contributors" style="height: 20px;">
43
+ </a>
44
+ <a href="https://opensource.org/licenses/Apache-2.0">
45
+ <img src="https://img.shields.io/badge/apache%202.0-blue.svg?style=flat-square&label=license" alt="license" style="height: 20px;">
46
+ </a>
47
+ <br>
48
+ </h4>
49
+
50
+ - [Source](https://github.com/techcode-io/proclet)
51
+ - [Documentation](https://github.com/techcode-io/proclet#readme)
52
+ - [Changelog](https://github.com/techcode-io/proclet/blob/main/CHANGELOG.md)
53
+ - [Issues](https://github.com/techcode-io/proclet/issues)
54
+ - [Contact](mailto:adrien.mannocci@gmail.com)
55
+
56
+ ## :package: Prerequisites
57
+
58
+ - [Python](https://www.python.org/downloads/) 3.12 or newer, on Linux, macOS or Windows.
59
+ - No runtime dependency.
60
+ - [uv](https://docs.astral.sh/uv/) to work on the project itself.
61
+
62
+ ## :sparkles: Features
63
+
64
+ - Ability to configure and run a command through a chainable, fully typed API.
65
+ - Ability to run the same command synchronously or with `asyncio`.
66
+ - Ability to redirect output to files, file objects, `StringIO`/`BytesIO` or a callable receiving each line.
67
+ - Ability to feed stdin from a string, bytes, a file object or a queue.
68
+ - Ability to chain commands into pipelines connected with raw OS pipes, safe for binary payloads.
69
+ - Ability to enforce timeouts and the exit codes that count as success.
70
+ - Ability to build the environment and `PATH` of a command from the current one.
71
+ - Ability to drop privileges to another user, group and set of supplementary groups.
72
+ - Ability to run a command with a lower CPU (and, on Linux, IO) priority.
73
+ - Ability to wrap a binary into a typed API of its own.
74
+ - Ability to observe every process spawn and exit.
75
+
76
+ ## :dart: Motivation
77
+
78
+ - We needed a way to run external tools from Python code without repeating `subprocess` boilerplate.
79
+ - Redirecting output to a logger, feeding stdin from a queue or chaining binary-safe pipelines shouldn't require hand-written threads.
80
+ - The same API should serve sync and `asyncio` code.
81
+ - The library should stay framework-agnostic: no runtime dependencies, no logging setup, failures are exceptions the caller decides about.
82
+
83
+ Streaming a database dump through a compressor, logging both tools' stderr line by line, with a timeout and an exit code check, looks like this with `subprocess`:
84
+
85
+ ```python
86
+ import logging
87
+ import subprocess
88
+ import threading
89
+
90
+ log = logging.getLogger(__name__)
91
+
92
+ dump = subprocess.Popen(
93
+ ["pg_dump", "shop"], stdout=subprocess.PIPE, stderr=subprocess.PIPE
94
+ )
95
+ pack = subprocess.Popen(
96
+ ["zstd", "-q", "-o", "shop.sql.zst"], stdin=dump.stdout, stderr=subprocess.PIPE
97
+ )
98
+ dump.stdout.close() # let pg_dump see a broken pipe if zstd dies
99
+
100
+
101
+ def forward(stream):
102
+ for line in stream:
103
+ log.warning(line.decode().rstrip("\n"))
104
+
105
+
106
+ threads = [threading.Thread(target=forward, args=(p.stderr,)) for p in (dump, pack)]
107
+ for thread in threads:
108
+ thread.start()
109
+ try:
110
+ dump.wait(timeout=600)
111
+ pack.wait(timeout=600)
112
+ finally:
113
+ for process in (dump, pack):
114
+ if process.poll() is None:
115
+ process.kill()
116
+ for thread in threads:
117
+ thread.join()
118
+ for process in (dump, pack):
119
+ if process.returncode != 0:
120
+ raise RuntimeError(f"{process.args} exited with {process.returncode}")
121
+ ```
122
+
123
+ With `proclet`:
124
+
125
+ ```python
126
+ import logging
127
+ from proclet import Command, strip_redirect
128
+
129
+ log = logging.getLogger(__name__)
130
+ to_log = strip_redirect(log.warning)
131
+
132
+ Command("pg_dump").args("shop").stderr(to_log).timeout(600).pipe(
133
+ Command("zstd").args("-q", "-o", "shop.sql.zst").stderr(to_log).timeout(600)
134
+ )
135
+ ```
136
+
137
+ ## :hammer: Workflow
138
+
139
+ ### Setup
140
+
141
+ The following steps will ensure your project is cloned properly.
142
+
143
+ 1. Clone repository:
144
+ ```shell
145
+ git clone https://github.com/techcode-io/proclet
146
+ cd proclet
147
+ ```
148
+ 2. Install dependencies and setup environment:
149
+ ```shell
150
+ uv sync
151
+ uv run poe env:configure
152
+ ```
153
+
154
+ ### Lint
155
+
156
+ - To lint you have to use the workflow.
157
+
158
+ ```bash
159
+ uv run poe lint
160
+ ```
161
+
162
+ - It will lint the project code using `ruff`.
163
+
164
+ ### Format
165
+
166
+ - To format you have to use the workflow.
167
+
168
+ ```bash
169
+ uv run poe fmt
170
+ ```
171
+
172
+ - It will format the project code using `ruff`, including the Python examples of this README.
173
+
174
+ ### Test
175
+
176
+ - To test you have to use the workflow.
177
+
178
+ ```bash
179
+ uv run poe test
180
+ ```
181
+
182
+ - It will run the test suite using `pytest`.
183
+ - `uv run poe ci` runs both lint and tests, as the CI does.
184
+
185
+ ## 📖 Usage
186
+
187
+ ### How to install
188
+
189
+ ```bash
190
+ pip install proclet
191
+ ```
192
+
193
+ ### How to run a command
194
+
195
+ ```python
196
+ from io import StringIO
197
+ from proclet import Command
198
+
199
+ out = StringIO()
200
+ Command("git").args("status", "--short").stdout(out).exec()
201
+ print(out.getvalue())
202
+ ```
203
+
204
+ - A command is configured with chainable setters, then run with `exec()`. Called without a value, most setters return the current one: `cmd.args()`, `cmd.env()`, `cmd.cwd()`...
205
+ - `exec()` waits for completion and returns the finished `subprocess.Popen`.
206
+ - Unless redirected, stdin reads from the null device and the output is discarded.
207
+
208
+ ### How to handle failures
209
+
210
+ ```python
211
+ from proclet import Command, CommandNotFound, ErrorReturnCode, TimeoutException
212
+
213
+ try:
214
+ plan = (
215
+ Command("terraform")
216
+ .args("plan", "-detailed-exitcode")
217
+ .ok_exit_codes(0, 2) # 2 means "changes pending", not a failure
218
+ .timeout(300)
219
+ .inherit()
220
+ .exec()
221
+ )
222
+ print("changes pending" if plan.returncode == 2 else "up to date")
223
+ except CommandNotFound as err:
224
+ print(f"{err.command} is not installed")
225
+ except ErrorReturnCode as err:
226
+ print(f"{err.cmd} failed with exit code {err.exit_code}")
227
+ except TimeoutException as err:
228
+ print(f"{err.cmd} took more than {err.timeout}s and was terminated")
229
+ ```
230
+
231
+ - `CommandNotFound` is raised at construction for a name missing from `PATH`; a `Path` is only checked when the command runs.
232
+ - `ErrorReturnCode` is raised for an exit code outside `ok_exit_codes(...)` (default: only `0`). A process killed by a signal reports a negative exit code.
233
+ - `TimeoutException` is raised once `timeout(...)` elapses; the process is terminated first.
234
+ - `proclet` never logs, prints or exits on its own: the caller decides what a failure means.
235
+
236
+ ### How to capture and stream output
237
+
238
+ ```python
239
+ import logging
240
+ from io import BytesIO, StringIO
241
+ from pathlib import Path
242
+ from proclet import Command, strip_redirect
243
+
244
+ log = logging.getLogger(__name__)
245
+
246
+ text = StringIO()
247
+ Command("git").args("log", "-1", "--format=%H").stdout(text).exec()
248
+
249
+ raw = BytesIO()
250
+ Command("git").args("show", "HEAD:logo.png").stdout(raw).exec()
251
+
252
+ Command("make").args("build").stdout(Path("build.log")).stderr(
253
+ strip_redirect(log.warning)
254
+ ).exec()
255
+ ```
256
+
257
+ - `stdout(...)` and `stderr(...)` accept a `Path` (truncated, then written), a file object (text or binary, including `StringIO`/`BytesIO`) or a callable.
258
+ - A callable receives each decoded line as it is produced, newline included: `strip_redirect(...)` wraps one to drop it, which suits loggers.
259
+ - `inherit()` wires stdin, stdout and stderr to the current process; `inherit_out()` only stdout and stderr, and `inherit_out(if_unset=True)` only the ones not redirected yet.
260
+
261
+ ### How to feed stdin
262
+
263
+ ```python
264
+ import threading
265
+ from queue import Queue
266
+ from proclet import Command
267
+
268
+ Command("sort").stdin("pear\napple\n").inherit_out().exec()
269
+
270
+ with open("data.csv", "rb") as source:
271
+ Command("wc").args("-l").stdin(source).inherit_out().exec()
272
+
273
+ lines: Queue[bytes | str | None] = Queue()
274
+
275
+
276
+ def produce() -> None:
277
+ for number in range(3):
278
+ lines.put(f"event {number}\n")
279
+ lines.put(None) # closes the command's stdin
280
+
281
+
282
+ threading.Thread(target=produce).start()
283
+ Command("cat").stdin(lines).inherit_out().exec()
284
+ ```
285
+
286
+ - `stdin(...)` accepts a `str` (encoded as UTF-8) or `bytes` payload, or a file object: one with a real file descriptor is handed to the child as is, others (`StringIO`/`BytesIO`) are read and fed.
287
+ - A queue streams items as they come and closes stdin when it yields `None`: a `queue.Queue` with `exec()`, an `asyncio.Queue` with `aexec()`.
288
+
289
+ ### How to run a command in the background
290
+
291
+ ```python
292
+ from proclet import Command
293
+
294
+ server = Command("python").args("-m", "http.server", "8000").exec(wait_completion=False)
295
+ try:
296
+ ... # talk to the server
297
+ finally:
298
+ server.terminate()
299
+ server.wait()
300
+ ```
301
+
302
+ - `exec(wait_completion=False)` returns the running `subprocess.Popen` as soon as it is spawned.
303
+ - `timeout(...)` and `ok_exit_codes(...)` aren't enforced then; redirect files are still closed once the process exits.
304
+
305
+ ### How to run commands with asyncio
306
+
307
+ ```python
308
+ import asyncio
309
+ from io import StringIO
310
+ from proclet import Command
311
+
312
+
313
+ async def uptimes(hosts: list[str]) -> dict[str, str]:
314
+ outputs = {host: StringIO() for host in hosts}
315
+ await asyncio.gather(
316
+ *(
317
+ Command("ssh").args(host, "uptime").stdout(out).timeout(10).aexec()
318
+ for host, out in outputs.items()
319
+ )
320
+ )
321
+ return {host: out.getvalue().strip() for host, out in outputs.items()}
322
+
323
+
324
+ print(asyncio.run(uptimes(["alpha", "beta", "gamma"])))
325
+ ```
326
+
327
+ - Every way of running a command has an `asyncio` counterpart prefixed with `a`: `aexec()`, `apipe()` and `apipeline()`. They return an `asyncio.subprocess.Process`.
328
+ - The configuration is shared: the same `Command` runs with either.
329
+
330
+ ### How to chain commands into a pipeline
331
+
332
+ ```python
333
+ from proclet import Command
334
+
335
+ Command("tar").args("-c", "data").pipeline(
336
+ Command("zstd").args("-q"),
337
+ Command("tee").args("data.tar.zst"),
338
+ )
339
+
340
+ Command("git").args("log", "--format=%an").pipe(
341
+ Command("sort").args("-u").inherit_out()
342
+ )
343
+ # or: await Command(...).apipeline(...) / .apipe(...)
344
+ ```
345
+
346
+ - `pipe(other)` connects two commands, `pipeline(*others)` any number of them; all stages run concurrently.
347
+ - Stages are connected with raw OS pipes, so binary payloads aren't decoded on the way.
348
+ - The first stage keeps its stdin, the last one its stdout; each stage keeps its own stderr, env, cwd, timeout and exit codes.
349
+ - Stages are checked in order: the first failure raises and the stages still running are terminated. The last stage's process is returned.
350
+
351
+ ### How to set the environment and PATH
352
+
353
+ ```python
354
+ from pathlib import Path
355
+ from proclet import Command, EnvCmd, PathCmd
356
+
357
+ env = (
358
+ EnvCmd.inherit(lambda key, _: key.startswith("LC_"))
359
+ .add({"PATH": PathCmd.inherit().add("/opt/tools/bin").build()})
360
+ .build()
361
+ )
362
+ Command("deploy").env(env).cwd(Path("infra")).exec()
363
+
364
+ Command("python", search_path=["/opt/python3.13/bin"]).args("--version").exec()
365
+ ```
366
+
367
+ - Without `env(...)` a command inherits the current environment; once set, it gets exactly that mapping, so build on `EnvCmd.inherit()` to keep it.
368
+ - `EnvCmd.inherit(predicate)` keeps only the variables `predicate(key, value)` accepts; `EnvCmd.empty()` starts from nothing.
369
+ - `PathCmd.add(...)` prepends a directory, so it takes precedence over the inherited `PATH`.
370
+ - `search_path` looks the binary up in the given directories instead of `PATH`.
371
+
372
+ ### How to drop privileges and lower priority
373
+
374
+ ```python
375
+ from proclet import Command
376
+
377
+ (
378
+ Command("rsync")
379
+ .args("-a", "src/", "dst/")
380
+ .user("backup") # requires sufficient privileges, e.g. root
381
+ .group("backup")
382
+ .extra_groups([]) # drop supplementary groups
383
+ .nice(19) # lowest priority
384
+ .exec()
385
+ )
386
+ ```
387
+
388
+ - `user`, `group` and `extra_groups` accept names or ids. They are POSIX only and raise `ValueError` elsewhere.
389
+ - `extra_groups` unset keeps the current supplementary groups; `[]` drops them all.
390
+ - `nice(...)` lowers the CPU priority; on Linux, `nice(19)` also puts the process in the idle IO class. On Windows the niceness maps to a priority class.
391
+
392
+ ### How to reuse a configuration
393
+
394
+ ```python
395
+ from pathlib import Path
396
+ from proclet import Command
397
+
398
+ base = Command("git").cwd(Path("repo")).timeout(30)
399
+ Command("git").copy(base).args("fetch", "--all").exec()
400
+ Command("git").copy(base).args("gc").exec()
401
+ ```
402
+
403
+ - `copy(other)` takes every setting of `other` (args, env, cwd, redirects, timeout, exit codes, privileges, niceness, observers) while keeping its own binary.
404
+
405
+ ### How to wrap a binary into a typed API
406
+
407
+ ```python
408
+ from io import StringIO
409
+ from pathlib import Path
410
+ from proclet import Bind, Command
411
+
412
+
413
+ class Git(Bind):
414
+ def __init__(self, repo: Path) -> None:
415
+ super().__init__("git")
416
+ self.cwd(repo)
417
+
418
+ def log(self, *refs: str) -> Command:
419
+ return self._command("log", "--oneline", *refs)
420
+
421
+ def current_branch(self) -> str:
422
+ out = StringIO()
423
+ self._command("branch", "--show-current").stdout(out).exec()
424
+ return out.getvalue().strip()
425
+
426
+
427
+ git = Git(Path("repo")).nice(10)
428
+ print(git.current_branch())
429
+ git.log("main").inherit_out().timeout(30).exec()
430
+ git.log("main", "--", "README.md").pipe(Command("wc").args("-l").inherit_out())
431
+ ```
432
+
433
+ - A `Bind` holds the context shared by every operation on its binary: `env`, `cwd`, `user`, `group`, `extra_groups`, `nice` and observers.
434
+ - Each operation calls `self._command(...)`, which returns a fresh `Command` carrying that context, then either returns it, for the caller to redirect, run or pipe (`log`), or runs it and returns a result (`current_branch`).
435
+ - Settings made on one operation's command never leak into another one.
436
+ - Set default context in the constructor, and share per-operation defaults through a private helper:
437
+
438
+ ```python
439
+ from proclet import Bind, Command, EnvCmd
440
+
441
+
442
+ class Terraform(Bind):
443
+ def __init__(self) -> None:
444
+ super().__init__("terraform")
445
+ self.env(EnvCmd.inherit().add({"TF_IN_AUTOMATION": "1"}).build())
446
+
447
+ def _run(self, *args: str) -> Command:
448
+ return self._command(*args).timeout(600)
449
+
450
+ def plan(self) -> bool:
451
+ """Whether changes are pending."""
452
+ plan = self._run("plan", "-detailed-exitcode").ok_exit_codes(0, 2).exec()
453
+ return plan.returncode == 2
454
+ ```
455
+
456
+ - A caller's `env(...)` replaces the bind's env: merge onto `bind.env()` to keep its defaults.
457
+
458
+ ### How to observe processes
459
+
460
+ ```python
461
+ import time
462
+ from proclet import Command, Process
463
+
464
+
465
+ class Timer:
466
+ def __init__(self) -> None:
467
+ self.started: dict[int, float] = {}
468
+
469
+ def on_spawn(self, process: Process) -> None:
470
+ self.started[process.pid] = time.monotonic()
471
+
472
+ def on_exit(self, process: Process) -> None:
473
+ elapsed = time.monotonic() - self.started.pop(process.pid)
474
+ print(f"pid {process.pid} exited with {process.returncode} in {elapsed:.2f}s")
475
+
476
+
477
+ Command("git").args("fetch").add_observer(Timer()).exec()
478
+ ```
479
+
480
+ - `add_observer(...)` registers any object implementing the `ProcessObserver` protocol, notified with `on_spawn(process)` and `on_exit(process)`; `Bind.add_observer(...)` watches every operation.
481
+ - Hooks run synchronously and must not raise. After `exec(wait_completion=False)`, `on_exit` runs on a background thread.
482
+
483
+ ## :heart: Contributing
484
+
485
+ If you find this project useful here's how you can help, please click the :eye: **Watch** button to avoid missing
486
+ notifications about new versions, and give it a :star2: **GitHub Star**!
487
+
488
+ You can also contribute by:
489
+
490
+ - Sending a [Pull Request](https://github.com/techcode-io/proclet/pulls) with your awesome new features and bug fixed.
491
+ - Be part of the community and help resolve [Issues](https://github.com/techcode-io/proclet/issues).
492
+
493
+ ## 🧾 License
494
+
495
+ The `proclet` project is free and open-source software licensed under the Apache-2.0 license.