py.io

The ‘py’ lib provides helper classes for capturing IO during execution of a program.

IO Capturing examples

py.io.StdCapture

Basic Example:

>>> import py
>>> capture = py.io.StdCapture()
>>> print "hello"
>>> out,err = capture.reset()
>>> out.strip() == "hello"
True

For calling functions you may use a shortcut:

>>> import py
>>> def f(): print "hello"
>>> res, out, err = py.io.StdCapture.call(f)
>>> out.strip() == "hello"
True

py.io.StdCaptureFD

If you also want to capture writes to the stdout/stderr filedescriptors you may invoke:

>>> import py, sys
>>> capture = py.io.StdCaptureFD(out=False, in_=False)
>>> sys.stderr.write("world")
>>> out,err = capture.reset()
>>> err
'world'

py.io object reference

class py.io.StdCaptureFD(out=True, err=True, mixed=False, in_=True, patchsys=True, now=True)[source]

This class allows to capture writes to FD1 and FD2 and may connect a NULL file to FD0 (and prevent reads from sys.stdin). If any of the 0,1,2 file descriptors is invalid it will not be captured.

resume()[source]

resume capturing with original temp files.

done(save=True)[source]

return (outfile, errfile) and stop capturing.

readouterr()[source]

return snapshot value of stdout/stderr capturings.

classmethod call(func, *args, **kwargs)

return a (res, out, err) tuple where out and err represent the output/error output during function execution. call the given function with args/kwargs and capture output/error during its execution.

reset()

reset sys.stdout/stderr and return captured output as strings.

suspend()

return current snapshot captures, memorize tempfiles.

class py.io.StdCapture(out=True, err=True, in_=True, mixed=False, now=True)[source]

This class allows to capture writes to sys.stdout|stderr “in-memory” and will raise errors on tries to read from sys.stdin. It only modifies sys.stdout|stderr|stdin attributes and does not touch underlying File Descriptors (use StdCaptureFD for that).

done(save=True)[source]

return (outfile, errfile) and stop capturing.

resume()[source]

resume capturing with original temp files.

readouterr()[source]

return snapshot value of stdout/stderr capturings.

classmethod call(func, *args, **kwargs)

return a (res, out, err) tuple where out and err represent the output/error output during function execution. call the given function with args/kwargs and capture output/error during its execution.

reset()

reset sys.stdout/stderr and return captured output as strings.

suspend()

return current snapshot captures, memorize tempfiles.

class py.io.TerminalWriter(file=None, stringio=False, encoding=None)[source]
chars_on_current_line

Return the number of characters written so far in the current line.

Please note that this count does not produce correct results after a reline() call, see #164.

New in version 1.5.0.

Return type:int
width_of_current_line

Return an estimate of the width so far in the current line.

New in version 1.6.0.

Return type:int