contextlib.redirect_stdout 总是一个好主意吗?

Is contextlib.redirect_stdout always a good idea?

自从我了解了该模式后,我就一直在使用

with open('myfile.txt','w') as myfile:
    with contextlib.redirect_stdout(myfile):
        # stuff
        print(...) # gets redirected to file

这让我可以使用打印语法(我更喜欢)写入文件,我可以轻松地将其注释掉以打印到屏幕以进行调试。但是,通过这样做,我将失去写入文件和屏幕的能力,并且可能编写不太清晰的代码。还有其他我应该知道的缺点吗?这是我应该使用的模式吗?

is this a pattern I should be using?

在这种特殊情况下,我确实认为您的模式不是惯用的,并且可能会混淆代码的 reader。内置的 print(因为这是一个 Python-3x 问题)已经有一个 file keyword argument,它将完全按照 redirect_stdout 在您的示例中执行的操作:

with open('myfile.txt', 'w') as myfile:
    print('foo', file=myfile)

并引入 redirect_stdout 只会让您的 reader 想知道您为什么不使用内置功能。 (就我个人而言,我发现嵌套 with 很难看。\ 分隔 with 更难看。)

至于注释掉的方便性(以及打印到 stdout 和文件),你可以有任意多的 print 调用,并根据需要注释掉它们需要

with open('myfile.txt', 'w') as myfile:
    print('foo')
    print('foo', file=myfile)

Are there any other disadvantages I should know about

除了它可能不是最佳解决方案(如本例)之外,我想不出任何确定的方案。

编辑:

来自doc:

Note that the global side effect on sys.stdout means that this context manager is not suitable for use in library code and most threaded applications. It also has no effect on the output of subprocesses.

This question,关于如何做你一直在做的事情,有很多关于重定向 stdout 的缺点的评论和答案,尤其是对其中一个答案的评论:

With disk caching performance of the original should be acceptable. This solution however has the drawback of ballooning the memory requirements if there were a lot of output. Though probably nothing to worry about here, it is generally a good idea to avoid this if possible. Same idea as using xrange (py3 range) instead of range, etc. – Gringo Suave