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**default_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 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')
- class
CompletedProcess
[source]¶A
NamedTuple
that holds a completed process’ information.
- 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 aChildProcessError
if the process, exits with a non-zero return code. Default:True
output_encoding (str, optional) – If set, the returned
stdout
andstderr
will be converted to from bytes to a Python string using this givenencoding
. Defaults to:None
which will use the value fromlocale.getpreferredencoding
or, if not set, the value fromsys.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 tosubprocess.run
.
- Type
__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 anydefault_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 givencmd
) 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