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
commandis executed, the command’s stdout and stderr outputs are captured in a pseudo terminal. The captured outputs are then added to this function’sstdoutandstderrIO 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’sstdoutto 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’sstderrto the terminal.columns (int, optional) – The number of character columns the pseudo terminal may use. If
force_dimensionsisFalse, this will be the fallback columns value when the the current terminal’s column size cannot be found. Ifforce_dimensionsisTrue, 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_dimensionsisFalse, this will be the fallback lines value when the the current terminal’s line size cannot be found. Ifforce_dimensionsisTrue, this will be actual character lines value. Defaults to:24.force_dimensions (bool, optional) – This controls how the given
columnsandlinesvalues are to be used. A value ofFalsewill use the givencolumnsandlinesas fallback values if the current terminal dimensions cannot be successfully queried. A value ofTruewill resize the pseudo terminal using the givencolumnsandlinesvalues. Defaults to:False.interactive (bool, optional) – A value of
Truewill interactively run the givencommand. Defaults to:False.**kwargs – Any additional key-word-arguments used with
Popen.stdoutandstderrwill 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=Trueand thebashexecutable cannot be located.OSError – Any errors raised when trying to read the pseudo terminal.
Example
An example using
runin 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
NamedTuplethat 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
Truewill raise aChildProcessErrorif the process, exits with a non-zero return code. Default:Trueoutput_encoding (str, optional) – If set, the returned
stdoutandstderrwill be converted to from bytes to a Python string using this givenencoding. Defaults to:Nonewhich will use the value fromlocale.getpreferredencodingor, if not set, the value fromsys.getdefaultencodingwill be used. If the given encoding does NOT exist the default will be used.**default_kwargs – Any
subprocess.Popenkeyword argument.
default_kwargs¶The
default_kwargspassed 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_kwargsset in the constructor.- Raises
FileNotFoundError – If the given
cmdcannot be found.ChildProcessError – If
raise_error=Truewas set in this class’ constructor; and, the process (from running the givencmd) returns a non-zero value.ValueError – If the given
**kwargshas 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