capture#

class capture(seq='', *args, **kwargs)[source]#

Bases: UserString, str, redirect_stdout

Captures stdout (e.g., from print()) as a variable.

Based on contextlib.redirect_stdout, but saves the user the trouble of defining and reading from an IO stream. Useful for testing the output of functions that are supposed to print certain output.

Examples:

# Using with...as
with sc.capture() as txt1:
    print('Assign these lines')
    print('to a variable')

# Using start()...stop()
txt2 = sc.capture().start()
print('This works')
print('the same way')
txt2.stop()

print('txt1:')
print(txt1)
print('txt2:')
print(txt2)

New in version 1.3.3.

Methods