Question Details

No question body available.

Tags

python windows pythonw

Answers (2)

February 11, 2026 Score: 0 Rep: 2,336 Quality: Low Completeness: 60%

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 printtostring(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 = printtostring(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")
February 11, 2026 Score: -1 Rep: 29,173 Quality: Medium Completeness: 60%

In a pythonw environment, sys.stdout will be None. However, you can still access the console via "CONOUT$".

Here's a portable approach that you could adapt to your current code:

import sys
import contextlib
import os

@contextlib.contextmanager def console(): def iswritable(handle): try: handle.write("") return True except Exception: pass return False

if iswritable(sys.stdout): try: yield sys.stdout finally: pass else: device = "CONOUT$" if os.name == "nt" else "/dev/tty" stdout = open(device, "a") try: yield stdout finally: stdout.close()

if name == "main": with console() as
console: print("Hello world!", file=console)

sys.stdout = None # sys.stdout will be None in pythonw

with console() as
console: print("Hello world!", file=_console)