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’sstdout
andstderr
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’sstdout
. Defaults to:sys.stdout
; which will output the command’sstdout
to the terminal.stderr (
typing.IO
, optional) – An input/output stream that will hold the command’sstderr
. Defaults to:sys.stderr
; which will output the command’sstderr
to the terminal.columns (int, optional) – The number of character columns the pseudo terminal may use. If
force_dimensions
isFalse
, this will be the fallback columns value when the the current terminal’s column size cannot be found. Ifforce_dimensions
isTrue
, 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
isFalse
, this will be the fallback lines value when the the current terminal’s line size cannot be found. Ifforce_dimensions
isTrue
, this will be actual character lines value. Defaults to:24
.force_dimensions (bool, optional) – This controls how the given
columns
andlines
values are to be used. A value ofFalse
will use the givencolumns
andlines
as fallback values if the current terminal dimensions cannot be successfully queried. A value ofTrue
will resize the pseudo terminal using the givencolumns
andlines
values. Defaults to:False
.interactive (bool, optional) – A value of
True
will interactively run the givencommand
. Defaults to:False
.**kwargs – Any additional key-word-arguments used with
Popen
.stdout
andstderr
will not be used if given in**kwargs
. Defaults to:{}
.- Return type
- Returns
int – The return value from running the given
command
- Raises
RuntimeError – When using
interactive=True
and thebash
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)