Redirection

sh can redirect the STDOUT and STDERR of a process to many different types of targets, using the _out and _err special kwargs.

Filename

If a string is used, it is assumed to be a filename. The filename is opened as “wb”, meaning truncate-write and binary mode.

import sh
sh.ifconfig(_out="/tmp/interfaces")

File-like Object

You may also use any object that supports .write(data), like io.StringIO:

import sh
from io import StringIO

buf = StringIO()
sh.ifconfig(_out=buf)
print(buf.getvalue())

Function Callback

A callback function may also be used as a target. The function must conform to one of three signatures:

fn(data)

The function takes just the chunk of data from the process.

fn(data, stdin_queue)

In addition to the previous signature, the function also takes a queue.Queue, which may be used to communicate programmatically with the process.

fn(data, stdin_queue, process)

In addition to the previous signature, the function takes a weakref.weakref to the OProc object.

See also

Output Callbacks