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: |

The optimal dimension of the avatar on Telegram is 512px by 512px, and it’s recommended to use PNG format to deliver an unpixelated avatar. In the “Bear Market Screaming Therapy Group” on Telegram, members are only allowed to post voice notes of themselves screaming. Anything else will result in an instant ban from the group, which currently has about 75 members. While some crypto traders move toward screaming as a coping mechanism, many mental health experts have argued that “scream therapy” is pseudoscience. Scientific research or no, it obviously feels good. Judge Hui described Ng as inciting others to “commit a massacre” with three posts teaching people to make “toxic chlorine gas bombs,” target police stations, police quarters and the city’s metro stations. This offence was “rather serious,” the court said. Activate up to 20 bots
from us


Telegram Python/ django
FROM American