将标准输出重定向到“无"在蟒蛇 [英] Redirecting stdout to "nothing" in python

查看:46
本文介绍了将标准输出重定向到“无"在蟒蛇的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个由足够多的模块组成的大型项目,每个模块都向标准输出打印一些东西.现在随着项目规模的扩大,有很多没有.print 语句在标准输出上打印了很多,这使程序变得相当慢.

I have a large project consisting of sufficiently large number of modules, each printing something to the standard output. Now as the project has grown in size, there are large no. of print statements printing a lot on the std out which has made the program considerably slower.

所以,我现在想在运行时决定是否向标准输出打印任何内容.我无法对模块进行更改,因为模块很多.(我知道我可以将标准输出重定向到一个文件,但即使这样也很慢.)

So, I now want to decide at runtime whether or not to print anything to the stdout. I cannot make changes in the modules as there are plenty of them. (I know I can redirect the stdout to a file but even this is considerably slow.)

所以我的问题是如何将标准输出重定向到空,即如何使 print 语句什么都不做?

So my question is how do I redirect the stdout to nothing ie how do I make the print statement do nothing?

# I want to do something like this.
sys.stdout = None         # this obviously will give an error as Nonetype object does not have any write method.

目前我唯一的想法是创建一个具有 write 方法(什么都不做)的类,并将标准输出重定向到此类的实例.

Currently the only idea I have is to make a class which has a write method (which does nothing) and redirect the stdout to an instance of this class.

class DontPrint(object):
    def write(*args): pass

dp = DontPrint()
sys.stdout = dp

python 中是否有内置机制?或者有什么比这更好的吗?

Is there an inbuilt mechanism in python for this? Or is there something better than this?

推荐答案

跨平台:

import os
import sys
f = open(os.devnull, 'w')
sys.stdout = f

在 Windows 上:

On Windows:

f = open('nul', 'w')
sys.stdout = f

在 Linux 上:

f = open('/dev/null', 'w')
sys.stdout = f

这篇关于将标准输出重定向到“无"在蟒蛇的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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