停止打印Python模块 [英] Stop Python Module from Printing

查看:35
本文介绍了停止打印Python模块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用一个名为eventregistry的模块,这是一个使用外部API的工具包.

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

与服务器建立连接时,我在其模块(导入为e_r)中调用此方法.

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!

有人知道某种"stopPrint()"函数可以让我调用方法并运行函数,但可以阻止它们打印到控制台吗?

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

例如

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

推荐答案

无需编辑模块,您就可以在一段时间内重新路由标准输出.

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

这篇关于停止打印Python模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆