Stop Python Module from Printing

泄露秘密 提交于 2021-02-10 16:01:36

问题


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"))

回答1:


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")



回答2:


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.



来源:https://stackoverflow.com/questions/42952623/stop-python-module-from-printing

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!