ARTICLE AD BOX
print() does not redirect global stdout when you pass file=…. Your append logic is fine, and pythonw only suppresses console output—it does not affect file writes.
If you want the formatted output of print() as a string (so you can safely write it yourself), capture it with io.StringIO:
import io import builtins def print_to_string(*args, **kwargs): buf = io.StringIO() builtins.print(*args, **kwargs, file=buf) return buf.getvalue()You can use this in your logger:
@classmethod def print(cls, *args, **kwargs): builtins.print(*args, **kwargs) # console (hidden under pythonw) if not cls.path: return text = print_to_string(*args, **kwargs) mode = "w" if cls.first else "a" cls.first = False with open(cls.path, mode, encoding="utf-8") as f: f.write(text) f.flush()This preserves all print() formatting (sep, end, etc.) and avoids buffering issues.
**Suggestions: ** For real applications, consider using the built-in logging module instead. You can check the following code sample:
import logging logging.basicConfig( level=logging.INFO, format="%(message)s", handlers=[ logging.FileHandler("log.txt"), logging.StreamHandler() ] ) logging.info("Hello world")