Skip to content

cmd

Execution of external commands with output forwarding.

This module provides a run function which starts a child process, forwards its output to a file-like object and installs signal handlers so that received termination signals are propagated to the child.

Example
import io
import py_misc_utils.cmd as cmd

buf = io.BytesIO()
rc = cmd.run(['python3', '-c', 'print(1 + 1)'], outfd=buf)

assert rc == 0
assert b'2' in buf.getvalue()

# String commands get template substitution (from tmpl_envs, or the
# environment) and shell-splitting: '$VAR' references are resolved
# before the command runs.
buf = io.BytesIO()
rc = cmd.run('echo $GREETING', outfd=buf, tmpl_envs=[dict(GREETING='hi')])

assert rc == 0
assert b'hi' in buf.getvalue()

run(cmd, outfd=None, tmpl_envs=None, **kwargs)

Run a child process, forwarding its output and signals.

The output is forwarded line-wise, and the child receives the termination signals (SIGINT/SIGTERM) delivered to the parent - the first reception of each signal is forwarded, subsequent ones are ignored.

The command can be given as a string -- in which case template variables are substituted from the provided environments before shell splitting -- or as an argument list.

Parameters:

Name Type Description Default
cmd

Command to run, as a template string or an argument list.

required
outfd

Optional file object to forward the process output to; defaults to the standard output.

None
tmpl_envs

Optional iterable of mappings used to resolve template variables in string commands.

None
**kwargs

Extra arguments forwarded to subprocess.Popen.

{}

Returns:

Type Description

The exit code of the child process.

Source code in py_misc_utils/cmd.py
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
def run(cmd, outfd=None, tmpl_envs=None, **kwargs):
  """Run a child process, forwarding its output and signals.

  The output is forwarded line-wise, and the child receives the
  termination signals (SIGINT/SIGTERM) delivered to the parent - the
  first reception of each signal is forwarded, subsequent ones are
  ignored.

  The command can be given as a string -- in which case template
  variables are substituted from the provided environments before shell
  splitting -- or as an argument list.

  Args:
    cmd: Command to run, as a template string or an argument list.
    outfd: Optional file object to forward the process output to;
      defaults to the standard output.
    tmpl_envs: Optional iterable of mappings used to resolve template
      variables in string commands.
    **kwargs: Extra arguments forwarded to subprocess.Popen.

  Returns:
    The exit code of the child process.
  """
  if isinstance(cmd, str):
    tmpl_envs = tmpl_envs or (os.environ,)
    cmd = tr.template_replace(cmd, lookup_fn=functools.partial(_lookup, tmpl_envs))
    cmd = shlex.split(cmd)

  alog.debug(f'Running: {cmd}')

  proc = subprocess.Popen(cmd,
                          stdout=subprocess.PIPE,
                          stderr=subprocess.STDOUT,
                          **kwargs)

  reader = _Reader(proc.stdout)
  writer = _Writer(outfd or sys.stdout)
  with sgn.Signals('INT, TERM', _SigHandler(proc, logfd=writer.fd)):
    while True:
      data = reader.read()
      if data:
        writer.write(data)
      elif proc.poll() is not None:
        break

  return proc.returncode