call_sys

privex.helpers.common.call_sys(proc, *args, write: Union[bytes, str] = None, **kwargs) → Union[Tuple[bytes, bytes], Tuple[str, str]][source]

A small wrapper around subprocess.Popen which allows executing processes, while optionally piping data (write) into the process’s stdin, then finally returning the process’s output and error results. Designed to be easier to use than using subprocess.Popen directly.

Using AsyncIO? - there’s a native python asyncio version of this function available in call_sys_async(), which uses the native asyncio.subprocess.create_subprocess_shell(), avoiding blocking IO.

By default, stdout and stdin are set to subprocess.PIPE while stderr defaults to subprocess.STDOUT. You can override these by passing new values as keyword arguments.

NOTE: The first positional argument is executed, and all other positional arguments are passed to the process in the order specified. To use call_sys’s arguments write, stdout, stderr and/or stdin, you MUST specify them as keyword arguments, otherwise they’ll just be passed to the process you’re executing.

Any keyword arguments not specified in the :param or :key pydoc specifications will simply be forwarded to the subprocess.Popen constructor.

Simple Example:

>>> # All arguments are automatically quoted if required, so spaces are completely fine.
>>> folders, _ = call_sys('ls', '-la', '/tmp/spaces are fine/hello world')
>>> print(stringify(folders))
backups  cache   lib  local  lock  log  mail  opt  run  snap  spool  tmp

Piping data into a process:

>>> data = "hello world"
>>> # The data "hello world" will be piped into wc's stdin, and wc's stdout + stderr will be returned
>>> out, _ = call_sys('wc', '-c', write=data)
>>> int(out)
11
Parameters
  • proc (str) – The process to execute.

  • args (str) – Any arguments to pass to the process proc as positional arguments.

  • write (bytes|str) – If this is not None, then this data will be piped into the process’s STDIN.

Key stdout

The subprocess file descriptor for stdout, e.g. subprocess.PIPE or subprocess.STDOUT

Key stderr

The subprocess file descriptor for stderr, e.g. subprocess.PIPE or subprocess.STDOUT

Key stdin

The subprocess file descriptor for stdin, e.g. subprocess.PIPE or subprocess.STDIN

Key cwd

Set the current/working directory of the process to this path, instead of the CWD of your calling script.

Return tuple output

A tuple containing the process output of stdout and stderr