Commands

flutils offers the following utilities for running commands.

run(command, stdout=None, stderr=None, columns=80, lines=24, force_dimensions=False, interactive=False, **kwargs)[source]

Run the given command line command and return the command’s return code.

When the given command is executed, the command’s stdout and stderr outputs are captured in a pseudo terminal. The captured outputs are then added to this function’s stdout and stderr IO objects.

This function will capture any ANSI escape codes in the output of the given command. This even includes ANSI colors.

Parameters
  • command (str, List[str], Tuple[str]) – The command to execute.

  • stdout (typing.IO, optional) – An input/output stream that will hold the command’s stdout. Defaults to: sys.stdout; which will output the command’s stdout to the terminal.

  • stderr (typing.IO, optional) – An input/output stream that will hold the command’s stderr. Defaults to: sys.stderr; which will output the command’s stderr to the terminal.

  • columns (int, optional) – The number of character columns the pseudo terminal may use. If force_dimensions is False, this will be the fallback columns value when the the current terminal’s column size cannot be found. If force_dimensions is True, this will be actual character column value. Defaults to: 80.

  • lines (int, optional) – The number of character lines the pseudo terminal may use. If force_dimensions is False, this will be the fallback lines value when the the current terminal’s line size cannot be found. If force_dimensions is True, this will be actual character lines value. Defaults to: 24.

  • force_dimensions (bool, optional) – This controls how the given columns and lines values are to be used. A value of False will use the given columns and lines as fallback values if the current terminal dimensions cannot be successfully queried. A value of True will resize the pseudo terminal using the given columns and lines values. Defaults to: False.

  • interactive (bool, optional) – A value of True will interactively run the given command. Defaults to: False.

  • **kwargs – Any additional key-word-arguments used with Popen. stdout and stderr will not be used if given in **default_kwargs. Defaults to: {}.

Return type

int

Returns

int – The return value from running the given command

Raises
  • RuntimeError – When using interactive=True and the bash executable cannot be located.

  • OSError – Any errors raised when trying to read the pseudo terminal.

Example

An example using run in code:

from flutils.cmdutils import run
from io import BytesIO
import sys
import os

home = os.path.expanduser('~')
with BytesIO() as stream:
    return_code = run(
        'ls "%s"' % home,
        stdout=stream,
        stderr=stream
    )
    text = stream.getvalue()
text = text.decode(sys.getdefaultencoding())
if return_code == 0:
    print(text)
else:
    print('Error: %s' % text)
prep_cmd(cmd)[source]

Convert a given command into a tuple for use by subprocess.Popen.

Parameters

cmd (Sequence) – The command to be converted.

This is for converting a command of type string or bytes to a tuple of strings for use by subprocess.Popen.

Example

>>> from flutils.cmdutils import prep_cmd
>>> prep_cmd('ls -Flap')
('ls', '-Flap')
Return type

Tuple[str, …]

class CompletedProcess[source]

A NamedTuple that holds a completed process’ information.

return_code

The process return code.

Type

int

stdout

All lines of the stdout from the process.

Type

str

stderr

All lines of the stderr from the process.

Type

str

cmd

The command that the process ran.

Type

str

class RunCmd(raise_error=True, output_encoding=None, **default_kwargs)[source]

A simple callable that simplifies many calls to subprocess.run.

Parameters
  • raise_error (bool, optional) – A value of True will raise a ChildProcessError if the process, exits with a non-zero return code. Default: True

  • output_encoding (str, optional) – If set, the returned stdout and stderr will be converted to from bytes to a Python string using this given encoding. Defaults to: None which will use the value from locale.getpreferredencoding or, if not set, the value from sys.getdefaultencoding will be used. If the given encoding does NOT exist the default will be used.

  • **default_kwargs – Any subprocess.Popen keyword argument.

default_kwargs

The default_kwargs passed into the constructor which may be passed on to subprocess.run.

Type

NamedTuple

output_encoding

The encoding used to decode the process output

Type

str

__call__(cmd, **kwargs)[source]

Run the given command and return the result.

Parameters
  • cmd (Sequence) – The command

  • **kwargs – Any default_kwargs to pass to subprocess.run. These default_kwargs will override any default_kwargs set in the constructor.

Raises
  • FileNotFoundError – If the given cmd cannot be found.

  • ChildProcessError – If raise_error=True was set in this class’ constructor; and, the process (from running the given cmd) returns a non-zero value.

  • ValueError – If the given **kwargs has invalid arguments.

Example

>>> from flutils.cmdutils import RunCmd
>>> from subprocess import PIPE
>>> import os
>>> run_command = RunCmd(stdout=PIPE, stderr=PIPE)
>>> result = run_command('ls -flap %s' % os.getcwd())
>>> result.return_code
0
>>> result.stdout
...
>>> result = run_command('ls -flap %s' % os.path.expanduser('~'))
Return type

CompletedProcess