如何抑制Python中特定模块和隐藏类方法的输出?

问题描述 投票:0回答:1

这是代码的样子

#!/usr/bin/env python3
#encoding:utf-8
import requests, numpy, fasttext, os, sys
from itertools import product
from math import sqrt

en_model=fasttext.load_model(path='crawl-300d-2M-subword.bin')

该脚本旨在使用某些NLP技术来训练分类模型。这是问题所在。

片段的最后一行,出于某些未知原因,即使没有错误运行,也向stderr输出空行。有什么方法可以从调用模块中抑制它,还是我必须侵入fasttext模块才能知道是哪行导致了此问题?总的来说,有什么方法可以抑制代码片段中的任何stdout或stderr回声,特别是当我知道它们是由导入的模块而不是我编写的模块引起的时候?

python-3.x echo stderr linefeed fasttext
1个回答
0
投票

您可以检查contextlib.redirect_stdout和contextlib.redirect_stderr

示例:

from contextlib import redirect_stdout
from contextlib import redirect_stderr
import os


def cache_stdouterr(func):
    def wrapper():
        with open(os.devnull,"w") as f:
            with redirect_stdout(f):
                with redirect_stderr(f):
                    func()
    return wrapper


@cache_stdouterr
def noprint():
    print("notprinted")

def toprint():
    print("shouldbeprinted")

toprint()
noprint()

# python3 test_redirect.py
shouldbeprinted

这是通用解决方案。对于您的特定问题,您可以尝试以下方法:

#!/usr/bin/env python3
#encoding:utf-8
import requests, numpy, fasttext, os, sys
from contextlib import redirect_stdout, redirect_stderr
from itertools import product
from math import sqrt

with redirect_stderr(open(os.devnull,"w")):
    en_model=fasttext.load_model(path='crawl-300d-2M-subword.bin')
© www.soinside.com 2019 - 2024. All rights reserved.