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 **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 tring 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 = stdout.getvalue()
text = text.decode(sys.getdefaultencoding())
if return_code == 0:
    print(text)
else:
    print('Error: %s' % text)