Assorted process and subprocess management functions.
Project description
Assorted process and subprocess management functions.
Latest release 20250513: print_argv: new as_str optional parameter to control conversion of arguments to strings.
Not to be confused with the excellent psutil package.
Short summary:
groupargv: Distribute the arrayargvover multiple arrays to fit withinMAX_ARGV. Return a list of argv lists.PidFileManager: Context manager for a pid file.pipefrom: Pipe text (usually) from a command usingsubprocess.Popen. Return thePopenobject with.stdoutas a pipe.pipeto: Pipe text to a command. Optionally trace invocation. Return the Popen object with .stdin encoded as text.prep_argv: A trite list comprehension to reduce an argument list*argvto the entries which are notNoneorFalseand to flatten other entries which are not strings.print_argv: Print an indented possibly folded command line.remove_pidfile: Truncate and remove a pidfile, permissions permitting.run: Run a command viasubprocess.run. Return theCompletedProcessresult orNoneifdoitis false.signal_handler: Context manager to push a new signal handler, yielding the old handler, restoring the old handler on exit. Ifcall_previousis true (defaultFalse) also call the old handler after the new handler on receipt of the signal.signal_handlers: Context manager to stack multiple signal handlers, yielding a mapping ofsig=>old_handler.stop: Stop the process specified bypid, optionally await its demise.write_pidfile: Write a process id to a pid file.
Module contents:
-
groupargv(pre_argv, argv, post_argv=(), max_argv=None, encode=False): Distribute the arrayargvover multiple arrays to fit withinMAX_ARGV. Return a list of argv lists.Parameters:
pre_argv: the sequence of leading argumentsargv: the sequence of arguments to distribute; this may not be emptypost_argv: optional, the sequence of trailing argumentsmax_argv: optional, the maximum length of each distributed argument list, default fromMAX_ARGV:131072encode: defaultFalse. If true, encode the argv sequences into bytes for accurate tallying. Ifencodeis a Boolean, encode the elements with their .encode() method. Ifencodeis astr, encode the elements with their.encode()method withencodeas the encoding name; otherwise presume thatencodeis a callable for encoding each element.
The returned argv arrays will contain the encoded element values.
-
PidFileManager(path, pid=None): Context manager for a pid file.Parameters:
path: the path to the process id file.pid: the process id to store in the pid file, default fromos.etpid.
Writes the process id file at the start and removes the process id file at the end.
-
pipefrom(argv, *, quiet: bool, remote=None, ssh_exe, text=True, stdin=-3, **popen_kw): Pipe text (usually) from a command usingsubprocess.Popen. Return thePopenobject with.stdoutas a pipe.Parameters:
argv: the command argument listquiet: optional flag, defaultFalse; if true, print the command tostderrtext: optional flag, defaultTrue; passed toPopen.stdin: optional value forPopen'sstdin, defaultDEVNULLOther keyword arguments are passed toPopen.
Note that
argvis passed throughprep_argvbefore use, allowing direct invocation with conditional parts. See theprep_argvfunction for details. -
pipeto(argv, *, quiet: bool, remote=None, ssh_exe, **kw): Pipe text to a command. Optionally trace invocation. Return the Popen object with .stdin encoded as text.Parameters:
argv: the command argument listtrace: if true (defaultFalse), iftraceisTrue, recite invocation to stderr otherwise presume thattraceis a stream to which to recite the invocation.
Other keyword arguments are passed to the
io.TextIOWrapperwhich wraps the command's input.Note that
argvis passed throughprep_argvbefore use, allowing direct invocation with conditional parts. See theprep_argvfunction for details. -
prep_argv(*argv, ssh_exe, remote=None): A trite list comprehension to reduce an argument list*argvto the entries which are notNoneorFalseand to flatten other entries which are not strings.This exists ease the construction of argument lists with methods like this:
>>> command_exe = 'hashindex' >>> hashname = 'sha1' >>> quiet = False >>> verbose = True >>> prep_argv( ... command_exe, ... quiet and '-q', ... verbose and '-v', ... hashname and ('-h', hashname), ... ) ['hashindex', '-v', '-h', 'sha1']where
verboseis aboolgoverning the-voption andhashnameis eitherstrto be passed with-h hashnameorNoneto omit the option.If
remoteis notNoneit is taken to be a remote host on which to runargv. This is done via thessh_exeargument, which defaults to the string'ssh'. The value ofssh_exeis a command string parsed withshlex.split. A newargvis computed as:[ *shlex.split(ssh_exe), remote, '--', shlex.join(argv), ] -
print_argv(*argv, indent0=None, indent='', subindent=' ', end='\n', file=None, fold=False, print=None, as_str=<class 'str'>): Print an indented possibly folded command line.Parameters:
argv: the arguments to printindent0: optional indent for the first argumentindent: optional per line indent iffoldis truesubindent: optional additional indent for the second and following lines, default" "end: optional line ending, default"\n"file: optional output file, defaultsys.stdoutfold: optional fold mode, defaultFalse; if true then arguments are laid out over multiple linesprint: optionalprintcallable, defaultbuiltins.printas_str: optional callable to convert arguments to strings, defaultstr; this can beNoneto avoid conversion
-
remove_pidfile(path): Truncate and remove a pidfile, permissions permitting. -
run(argv, *, check=True, doit: bool, input=None, logger=None, print=None, fold=None, quiet: bool, remote=None, ssh_exe=None, stdin=None, **subp_options): Run a command viasubprocess.run. Return theCompletedProcessresult orNoneifdoitis false.Positional parameter:
argv: the command line to run
Note that
argvis passed throughprep_argv(argv,remote=remote,ssh_exe=ssh_exe)before use, allowing direct invocation with conditional parts. See theprep_argvfunction for details.Keyword parameters:
check: passed tosubprocess.run, defaultTrue; NB: unlike thesubprocess.rundefault, which isFalsedoit: optional flag, defaultTrue; if false do not run the command and returnNonefold: optional flag, passed toprint_argvinput: defaultNone: alternative tostdin; passed tosubprocess.runlogger: optional logger, defaultNone; ifTrue, uselogging.getLogger(); if notNoneorFalsetrace usingprint_argvquiet: defaultFalse; if false, print the command and its outputremote: optional remote target on which to runargvssh_exe: optional command string for the remote shellstdin: standard input for the subprocess, defaultsubprocess.DEVNULL; passed tosubprocess.run
Other keyword parameters are passed to
subprocess.run. -
signal_handler(sig, handler, call_previous=False): Context manager to push a new signal handler, yielding the old handler, restoring the old handler on exit. Ifcall_previousis true (defaultFalse) also call the old handler after the new handler on receipt of the signal.Parameters:
sig: theintsignal number to catchhandler: the handler function to call with(sig,frame)call_previous: optional flag (defaultFalse); if true, also call the old handler (if any) afterhandler
-
signal_handlers(sig_hnds, call_previous=False, _stacked=None): Context manager to stack multiple signal handlers, yielding a mapping ofsig=>old_handler.Parameters:
sig_hnds: a mapping ofsig=>new_handleror an iterable of(sig,new_handler)pairscall_previous: optional flag (defaultFalse), passed tosignal_handler()
-
stop(pid, signum=<Signals.SIGTERM: 15>, wait=None, do_SIGKILL=False): Stop the process specified bypid, optionally await its demise.Parameters:
pid: process id. Ifpidis a string, treat as a process id file and read the process id from it.signum: the signal to send, defaultsignal.SIGTERM.wait: whether to wait for the process, defaultNone. IfNone, returnTrue(signal delivered). If0, wait indefinitely until the process exits as tested byos.kill(pid, 0). If greater than 0, wait up towaitseconds for the process to die; if it exits, returnTrue, otherwiseFalse;do_SIGKILL: if true (defaultFalse), send the processsignal.SIGKILLas a final measure before return.
-
write_pidfile(path, pid=None): Write a process id to a pid file.Parameters:
path: the path to the pid file.pid: the process id to write, defautl fromos.getpid.
Release Log
Release 20250513: print_argv: new as_str optional parameter to control conversion of arguments to strings.
Release 20250108.1: print_argv: new indent0 parameter to use a different indent for the first line.
Release 20250108: run: accept new optional fold= parameter, plumb to print_argv.
Release 20241206: run(): accept new remote= and ssh_exe= parameters to support remote execution, default via @uses_cmd_options(ssh_exe).
Release 20241122:
- print_argv: new print= parameter to provide a print() function, refactor to use print instead of file.write.
- run: new optional print parameter, plumb to print_argv.
- Use @uses_doit and @uses_quiet to provide the default quiet and doit states.
Release 20240316: Fixed release upload artifacts.
Release 20240211:
- run: new optional input= parameter to presupply input data.
- New prep_argv(*argv) function to flatten and trim computes argv lists; use automatically in run(), pipeot(), pipefrom().
Release 20231129: run(): default stdin=subprocess.DEVNULL.
Release 20230612:
- pipefrom: default stdin=DEVNULL.
- Make many parameters keyword only.
Release 20221228:
- signal_handlers: bugfix iteration of sig_hnds.
- Use cs.gimmicks instead of cs.logutils.
- Drop use of cs.upd, fixes circular import; users of run() may need to call "with Upd().above()" themselves.
Release 20221118: run: do not print cp.stdout.
Release 20220805: run: print trace to stderr.
Release 20220626: run: default quiet=True.
Release 20220606:
- run: fold in the superior run() from cs.ebooks.
- pipefrom,pipeto: replace trace= with quiet= like run().
- print_argv: add an
endparameter (used by pipefrom).
Release 20220531:
- New print_argv function for writing shell command lines out nicely.
- Bump requirements for cs.gimmicks.
Release 20220504: signal_handlers: reshape try/except to avoid confusing traceback.
Release 20220429:
- New signal_handler(sig,handler,call_previous=False) context manager to push a signal handler.
- New signal_handlers() context manager to stack handlers for multiple signals.
Release 20190101: Bugfix context manager cleanup. groupargv improvements.
Release 20171112: Bugfix array length counting.
Release 20171110: New function groupargv for breaking up argv lists to fit within the maximum argument limit; constant MAX_ARGV for the default limit.
Release 20171031: run: accept optional pids parameter, a setlike collection of process ids.
Release 20171018:
run: replace trace parameter with logger, default None
Release 20170908.1: remove dependency on cs.pfx
Release 20170908: run: pass extra keyword arguments to subprocess.call
Release 20170906.1: Add run, pipefrom and pipeto - were incorrectly in another module.
Release 20170906: First PyPI release.
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file cs_psutils-20250513.tar.gz.
File metadata
- Download URL: cs_psutils-20250513.tar.gz
- Upload date:
- Size: 10.4 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.1.0 CPython/3.13.1
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
9026be71d3d3514052eba38227706cc83ddf53a5625c25335beb83a36b2719fe
|
|
| MD5 |
322d471846bc14ead2f7e92f80e1f9be
|
|
| BLAKE2b-256 |
a8a70bc12e421745dc2b88cf91d23273d56286c6d2e1f699d3ff3b318ff53c49
|
File details
Details for the file cs_psutils-20250513-py2.py3-none-any.whl.
File metadata
- Download URL: cs_psutils-20250513-py2.py3-none-any.whl
- Upload date:
- Size: 10.6 kB
- Tags: Python 2, Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.1.0 CPython/3.13.1
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
77e9c3161c8e8219f5e89492a6fe1554894f12464351073d2473d3d44ff52204
|
|
| MD5 |
8de5de55a11a09050c6021047785aa5c
|
|
| BLAKE2b-256 |
cae7b07b233a7dc341429f43a7e66204767c5209af362c01a00c7d32ca66b8b1
|