Tee¶
- class giant.utilities.tee.Tee(file, redirect=REDIRECT.STDOUT, mode='a+', buff=-1)[source]¶
This class support simultaneously writing to a file and stdout/stderr
Essentially, all this does is serially call the write method for the original stdout/stderr object followed by the write method for the file being teed to. This is also a context manager so you can use it with a
with
block for automatic opening/closing. If not using in a with block, you should callclose()
when done to set things back to normal.Example:
>>> from giant.utilities.tee import Tee, REDIRECT >>> with Tee('mylog.txt', redirect=REDIRECT.STDOUT): ... print('first line') ... print('Second line') ... print('I like tacos!!') first line second line I like tacos!! >>> with open('mylog.txt', 'r') as ifile: ... print(ifile.readlines()) ['first line\n', 'second line\n', 'I like tacos!!\n']
Non-context manager example:
>>> from giant.utilities.tee import Tee, REDIRECT >>> mytee = Tee('mylog.txt', redirect=REDIRECT.STDOUT) >>> print('first line') first line >>> print('second line') second line >>> print('I like tacos!!') I like tacos!! >>> mytee.close() >>> with open('mylog.txt', 'r') as ifile: ... print(ifile.readlines()) ['first line\n', 'second line\n', 'I like tacos!!\n']
inspiration: https://stackoverflow.com/a/24583265/3431189
- Parameters:
file (Path | str | IO) – The file to write to as a string or a
IO
object which defines write, flush, and close methods.redirect (REDIRECT | str) – Whether to redirect STDOUT or STDERR to the file.
mode (str) – The mode to open the file with. Should be either ‘w’, ‘a+’, or ‘r+’. Ignored if
file
isIO
buff (int) – How to buffer the file. Should be -1 (for system default) or >= 1. Ignored if
file
isIO
- file: IO | None¶
The file object to tee to or
None
if this is closed.
- stdout: IO | None¶
A copy of the original STDOUT when
redirect
is set toSTDOUT
and this is open, otherwiseNone
- stderr: IO | None¶
A copy of the original STDERR when
redirect
is set toSTDERR
and this is closed, otherwiseNone
Summary of Methods
This method dispatches to both the file write method and stdout or stderr depending on what was selected at initialization for the |
|
This method flushes all data by calling both the file flush method and stdout or stderr's flush method depending on what was selected at initialization for the |
|
This method closes the file object and resets stdout/stderr to their values before creating an instance of this class. |