Lewis Anderson
Lewis Anderson

Reputation: 691

Stop Python Module from Printing

I am using a module called eventregistry, which is a toolkit for using an external API.

When the connection is made with the server, I call this method on their module (imported as e_r).

er = e_r.EventRegistry(apiKey="1234")

The module method then internally prints:

using user provided API key for making requests
Event Registry host: http://eventregistry.org

Which just clogs up my console, which I only want to print on when one of my data sources throws an error. I'm doing multiple requests to this datasource, and its really getting very messy in the console!

Is anyone aware of some kind of "stopPrint()" function that allows me to call methods and run functions, but stop them printing to console?

E.g.

er = stopPrint(e_r.EventRegistry(apiKey="1234"))

Upvotes: 5

Views: 5861

Answers (2)

gbtimmon
gbtimmon

Reputation: 4332

Without editing the module you can reroute the stdout for a while.

import sys
import os

def stopPrint(func, *args, **kwargs):
    with open(os.devnull,"w") as devNull:
        original = sys.stdout
        sys.stdout = devNull
        func(*args, **kwargs)
        sys.stdout = original 

stopPrint(e_r.EventRegistry,apiKey="1234")

Better, you can register a suppressed function by replacing the methods with a wrapped version by using something similar to the decorator pattern.

def suppressOutput(func):
    def wrapper(*args, **kwargs):
        with open(os.devnull,"w") as devNull:
            original = sys.stdout
            sys.stdout = devNull
            func(*args, **kwargs)
            sys.stdout = original
    return wrapper

e_r.EventRegistry = suppressOutput(e_r.EventRegistry)

# As many times as I want, stdout should always be suppressed. 
e_r.EventRegistry(apiKey="1234")
e_r.EventRegistry(apiKey="1234")
e_r.EventRegistry(apiKey="1234")
e_r.EventRegistry(apiKey="1234")

And just for the trifecta of solutions here is a context manager based approach!!

from contextlib import contextmanager
import sys
import os

@contextmanager
def suppressStream(stream):
    with open(os.devnull, "w") as devNull:
        orig = stream
        stream = devNull
        try:  
            yield
        finally:
            stream = orig

with suppressStream(sys.stdout):
    e_r.EventRegistry(apiKey="1234")

with suppressStream(sys.stderr):
    e_r.EventRegistry(apiKey="1234")

Upvotes: 7

Sadie LaBounty
Sadie LaBounty

Reputation: 379

One way of doing this is just to edit the module itself. Simply open EventRegistry.py and remove the

if apiKey:
    print("using user provided API key for making requests")

and

print("Event Registry host: %s" % (self._host))

lines of code. You may then need to reinstall the module with setup.py.

Upvotes: 0

Related Questions