PYTHONL Telegram 4982
🖥 Контекстный перехват stdout — как легко отключить или сохранить print

💡 Хотите, чтобы print() не мешал логике и при этом легко отключался или сохранялся в файл?

Вместо того чтобы комментировать все print() в проде, подмените стандартный вывод через контекстный менеджер — и легко направляйте вывод в файл, /dev/null или даже буфер для последующей обработки.

Это особенно полезно при отладке в прод-среде или при генерации логов без сторонних библиотек.


import sys
from contextlib import contextmanager
from io import StringIO
import os

@contextmanager
def capture_stdout(to_file=None, suppress=False):
original_stdout = sys.stdout
try:
if suppress:
sys.stdout = open(os.devnull, 'w')
elif to_file:
sys.stdout = open(to_file, 'w')
else:
buffer = StringIO()
sys.stdout = buffer
yield sys.stdout
finally:
sys.stdout.close() if sys.stdout not in (original_stdout, sys.__stdout__) else None
sys.stdout = original_stdout

# Пример использования:
with capture_stdout(suppress=True):
print("Этого вы не увидите")

with capture_stdout(to_file="output.log"):
print("А это уйдёт в файл")

with capture_stdout() as captured:
print("Это записано во внутренний буфер")

print("Буфер содержит:", captured.getvalue().strip())


@pythonl
Please open Telegram to view this post
VIEW IN TELEGRAM
👍98🔥4😁3



tgoop.com/pythonl/4982
Create:
Last Update:

🖥 Контекстный перехват stdout — как легко отключить или сохранить print

💡 Хотите, чтобы print() не мешал логике и при этом легко отключался или сохранялся в файл?

Вместо того чтобы комментировать все print() в проде, подмените стандартный вывод через контекстный менеджер — и легко направляйте вывод в файл, /dev/null или даже буфер для последующей обработки.

Это особенно полезно при отладке в прод-среде или при генерации логов без сторонних библиотек.


import sys
from contextlib import contextmanager
from io import StringIO
import os

@contextmanager
def capture_stdout(to_file=None, suppress=False):
original_stdout = sys.stdout
try:
if suppress:
sys.stdout = open(os.devnull, 'w')
elif to_file:
sys.stdout = open(to_file, 'w')
else:
buffer = StringIO()
sys.stdout = buffer
yield sys.stdout
finally:
sys.stdout.close() if sys.stdout not in (original_stdout, sys.__stdout__) else None
sys.stdout = original_stdout

# Пример использования:
with capture_stdout(suppress=True):
print("Этого вы не увидите")

with capture_stdout(to_file="output.log"):
print("А это уйдёт в файл")

with capture_stdout() as captured:
print("Это записано во внутренний буфер")

print("Буфер содержит:", captured.getvalue().strip())


@pythonl

BY Python/ django


Share with your friend now:
tgoop.com/pythonl/4982

View MORE
Open in Telegram


Telegram News

Date: |

A Hong Kong protester with a petrol bomb. File photo: Dylan Hollingsworth/HKFP. Joined by Telegram's representative in Brazil, Alan Campos, Perekopsky noted the platform was unable to cater to some of the TSE requests due to the company's operational setup. But Perekopsky added that these requests could be studied for future implementation. Hashtags Telegram is a leading cloud-based instant messages platform. It became popular in recent years for its privacy, speed, voice and video quality, and other unmatched features over its main competitor Whatsapp. The administrator of a telegram group, "Suck Channel," was sentenced to six years and six months in prison for seven counts of incitement yesterday.
from us


Telegram Python/ django
FROM American