How to Block Calls to Print

How to block calls to print?

Python lets you overwrite standard output (stdout) with any file object. This should work cross platform and write to the null device.

import sys, os

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

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

print 'This will print'

blockPrint()
print "This won't"

enablePrint()
print "This will too"

If you don't want that one function to print, call blockPrint() before it, and enablePrint() when you want it to continue. If you want to disable all printing, start blocking at the top of the file.

Any way to suppress output from print calls?

This cannot silence the print because print is executed before silence:

silence(print('hello'))

On the other hand, you could do this:

@contextlib.contextmanager
def silence():
sys.stdout, old = io.StringIO(), sys.stdout
try:
yield
finally:
sys.stdout = old

with silence():
print('hello')

All the prints are redirected to an io.StringIO object while in the silence() context.
You may also choose to do something with the collected prints at the end of the context.

Python + Disabled print output, and can't get it back

You need to store the old stdin so that you can restore it:

import sys
import os

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

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

blockPrint()
print("test")
enablePrint()
print("test")

will print test once. Furthermore I'd recommend the use of a contextmanager:

from contextlib import contextmanager

@contextmanager
def blockPrint():
import sys
old_stdout = sys.stdout
sys.stdout = None
try:
yield
finally:
sys.stdout = old_stdout

with blockPrint():
print("test")

print("test")

which will again print test just once.

Edit: For those wondering why this can benecessary: Under some circumstances sys.__stdout__ can be None (see https://docs.python.org/3/library/sys.html) - For me this is for example the case in a Python 3.5 shell within IDLE on Windows.

Python 3.5.2 (v3.5.2:4def2a2901a5, Jun 25 2016, 22:01:18) [MSC v.1900 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> import sys
>>> repr(sys.__stdout__)
'None'
>>> repr(sys.stdout)
'<idlelib.PyShell.PseudoOutputFile object at 0x03ACF8B0>'

How to use a with statement to disable printing?

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

Avoid `print` calls in production code. (Documentation)

It is because of the flutter_lints package which is implicitly added to new projects created after Flutter 2.3.0.

You can use any of the following solutions.

  1. To remove the warning in that single line:

    // ignore: avoid_print
    print('Hello World');
  2. To remove the warning in that file

    // ignore_for_file: avoid_print
    print('Hello World');
  3. To remove the warning from the whole project.

    Open analysis_options.yaml file and add this linter rule:

    include: package:flutter_lints/flutter.yaml

    linter:
    rules:
    avoid_print: false

How to prevent subprocess.call from printing return code?

You can use subprocess.check_output() instead of subprocess.call():

import subprocess

print("The top five memory consumers on the system are:")

cmd = "ps -eo pid,ppid,cmd,%mem,%cpu --sort=-%mem | head -n 6"
result = subprocess.check_output(cmd, shell=True).decode()

lines = result.split("\n")
for line in lines:
print(line)

Also note that the result of check_output() is a bytes-like object, so you must call .decode() on it if you want to work with it as a string.

Disable all prints except the ones done in the called function

You can save the reference to the print function in a variable orig_print and override print with a function that does nothing, and then use a decorator on the function you want to allow printing to rename all calls to print to orig_print with a ast.NodeTransformer subclass:

from __future__ import print_function
import inspect
import ast
from textwrap import dedent

orig_print = print
print = lambda *args, **kwargs: None

class EnablePrint(ast.NodeTransformer):
# remove the enable_print decorator from the decorator list so the transformed
# function won't be re-decorated when executed
def visit_FunctionDef(self, node):
node.decorator_list = [
decorator for decorator in node.decorator_list
if not isinstance(decorator, ast.Name) or decorator.id != 'enable_print'
]
self.generic_visit(node)
return node

def visit_Call(self, node):
if node.func.id == 'print':
node.func.id = 'orig_print'
return node

def enable_print(func):
node = ast.parse(dedent(inspect.getsource(func)))
EnablePrint().visit(node)
scope = {}
exec(compile(node, inspect.getfile(func), 'exec'), func.__globals__, scope)
return scope[func.__name__]

so that:

def func():
print("Inside func")

@enable_print
def my_func():
print("Starting inside my_func ")
func()
print("In my_func")
func()

my_func()

would output:

Starting inside my_func 
In my_func


Related Topics



Leave a reply



Submit