-1

I want to use something like this:

print('Hello')
with dont_print():
    print('some other text')
    print('more text')

print('World')

The output should be:

Hello
World

So everything inside the dont_print won't get printed. How can I get a function like this?

Chris_Rands
  • 38,994
  • 14
  • 83
  • 119
user38
  • 151
  • 1
  • 14
  • Have you seen the context manager [`redirect_stdout`](https://docs.python.org/3/library/contextlib.html#contextlib.redirect_stdout)? – ikkuh Aug 07 '19 at 11:28

3 Answers3

2
from unittest.mock import patch

print('Hello')
with patch('builtins.print'):
    print('some other text')
    print('more text')

print('World')
ipaleka
  • 3,745
  • 2
  • 13
  • 33
1

Overwrite your standard output to some file object. Here is your modified version.

import sys, os

# Disable
def blockPrint():
    sys.stdout = open(os.devnull, 'w')

# Restore
def enablePrint():
    sys.stdout = sys.__stdout__


print('Hello')

blockPrint()
print('some other text')
print('more text')

enablePrint()
print('World')

More on this here

0

You can use redirect_stdout as context manager to redirect stdout to nothingness with os.devnull:

import os
from contextlib import redirect_stdout

print('Hello')
with open(os.devnull, 'w') as f:
    with redirect_stdout(f):
        print('some other text')
        print('more text')
print('World')
ikkuh
  • 4,473
  • 3
  • 24
  • 39