capture_output

(class from pyomo.common.tee)

class pyomo.common.tee.capture_output(output=None, capture_fd=False)[source]

Bases: object

Context manager to capture output sent to sys.stdout and sys.stderr

This is a drop-in substitute for PyUtilib’s capture_output to temporarily redirect output to the provided stream or file.

Parameters:
  • output (io.TextIOBase, Sequence[io.TextIOBase], TeeStream, str, or None) – Output stream where all captured stdout/stderr data is sent. If a str is provided, it is used as a file name and opened (potentially overwriting any existing file). If None, a io.StringIO object is created and used.

  • capture_fd (bool) –

    If True, we will also redirect the process file descriptors 1 (stdout), 2 (stderr), and the file descriptors from sys.stdout.fileno() and sys.stderr.fileno() to the output. This is useful for capturing output emitted directly to the process stdout / stderr by external compiled modules.

    Capturing and redirecting the file descriptors can cause loops in the output stream (where one of the output streams points to a file descriptor we just captured). capture_output will attempt to locate io.IOBase streams in output that point to file descriptors that we just captured and replace them with temporary streams that point to (copies of) the original file descriptor. In addition, capture_output will look for LogStream objects and will attempt to locate logging.StreamHandle objects that would output to a redirected file descriptor and temporarily redirect those handlers to (copies of) the original file descriptor.

    Note that this process will cover the most common cases, but is by no means perfect. Use of other output classes or customized log handlers may still result in output loops (usually manifesting in an error message about text being left in the output buffer).

Returns:

This is the output stream object where all data is sent.

Return type:

io.TextIOBase

__init__(output=None, capture_fd=False)[source]

Methods

__init__([output, capture_fd])

reset()

setup()

Member Documentation