禁止在库外部调用模块的输出 [英] Suppressing output of module calling outside library

查看:70
本文介绍了禁止在库外部调用模块的输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用机器学习库 PyML 时,我遇到了一个烦人的问题. PyML使用 libsvm 来训练SVM分类器.问题是libsvm将一些文本输出到标准输出.但是因为那是在Python之外,所以我无法拦截它.我尝试使用问题

I have an annoying problem when using machine learning library PyML. PyML uses libsvm to train the SVM classifier. The problem is that libsvm outputs some text to standard output. But because that is outside of Python I cannot intercept it. I tried using methods described in problem Silence the stdout of a function in Python without trashing sys.stdout and restoring each function call but none of those help.

有什么办法可以做到这一点.不能修改PyML.

Is there any way how to do this. Modifying PyML is not an option.

推荐答案

打开/dev/null进行写入,使用os.dup()复制stdout,然后使用os.dup2()将打开的/dev/null复制到stdout.使用os.dup2()将复制的标准输出复制到实际的标准输出.

Open /dev/null for writing, use os.dup() to copy stdout, and use os.dup2() to copy your open /dev/null to stdout. Use os.dup2() to copy your copied stdout back to the real stdout after.

devnull = open('/dev/null', 'w')
oldstdout_fno = os.dup(sys.stdout.fileno())
os.dup2(devnull.fileno(), 1)
makesomenoise()
os.dup2(oldstdout_fno, 1)

这篇关于禁止在库外部调用模块的输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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