Edit: Since it appears that there\'s either no solution, or I\'m doing something so non-standard that nobody knows - I\'ll revise my question to also ask: What is the best w
You can also add stderr
as well, based on shx2's answer above using class multifile
:
class Log(object):
def __init__(self, path_log, mode="w", encoding="utf-8"):
h = open(path_log, mode, encoding=encoding)
sys.stdout = multifile([ sys.stdout, h ])
sys.stderr = multifile([ sys.stderr, h ])
def __enter__(self):
""" Necessary if called by with (or with... as) """
return self # only necessary if "as"
def __exit__(self, type, value, tb):
""" Necessary if call by with """
pass
def __del__(self):
if sys is not None:
# restoring
sys.stdout = sys.__stdout__
sys.stderr = sys.__stderr__
log = Log("test.txt")
print("line 1")
print("line 2", file=sys.stderr)
del log
print("line 3 only on screen")