contextlib.redirect_stdout总是一个好主意吗? [英] Is contextlib.redirect_stdout always a good idea?
问题描述
自从我了解了这种模式以来,我一直在使用
Since I've learned of the pattern, I've been using
with open('myfile.txt','w') as myfile:
with contextlib.redirect_stdout(myfile):
# stuff
print(...) # gets redirected to file
这使我可以使用打印语法(我更喜欢)来写入文件,并且我可以轻松地将其注释掉以打印到屏幕上进行调试.但是,这样做会消除我同时写入文件和屏幕的能力,并且可能会编写不太清晰的代码.还有其他我应该知道的缺点吗?这是我应该使用的模式吗?
This lets me use the print syntax (which I prefer) to write to files and I can easily comment it out to print to screen for debug. However, by doing this, I am removing my ability to both write to file and to the screen, and possibly writing less clear code. Are there any other disadvantages I should know about, and is this a pattern I should be using?
推荐答案
这是我应该使用的模式吗?
is this a pattern I should be using?
在这种情况下,我确实认为您的模式不是惯用的,并且可能会使您的代码阅读者感到困惑.内置的print
(因为这是一个Python-3x问题)已经具有 file
关键字参数,它将与您的示例中的redirect_stdout
完全相同:
In this particular case, I do think your pattern is not idiomatic, and potentially confusing to the reader of your code. The builtin print
(since this is a Python-3x question) already has a file
keyword argument which will do exactly what redirect_stdout
does in your example:
with open('myfile.txt', 'w') as myfile:
print('foo', file=myfile)
并引入redirect_stdout
只会使您的读者纳闷为什么不使用内置功能. (就我个人而言,我发现嵌套的with
丑陋.\
分隔的with
更加丑陋.)
and introducing redirect_stdout
only makes your reader wonder why you don't use the builtin feature. (And personally, I find nested with
ugly. \
-separated with
even more ugly.)
为了便于注释(以及打印到stdout
和文件中),您可以根据需要进行任意数量的print
调用,并根据需要将它们注释掉
As for the ease of commenting out (and for printing to both stdout
and a file), well you can have as many print
calls as you like, and comment them out as you need
with open('myfile.txt', 'w') as myfile:
print('foo')
print('foo', file=myfile)
我应该知道还有其他缺点吗?
Are there any other disadvantages I should know about
除了它可能不是最好的解决方案(在这种情况下)之外,我没有什么可以确定的.
Nothing definite I can think of, except that it may not be the best solution (as in this case).
来自文档:
请注意,对sys.stdout的全局副作用意味着此上下文 管理器不适合在库代码和大多数线程中使用 应用程序.它还对子流程的输出没有影响.
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.
这篇关于contextlib.redirect_stdout总是一个好主意吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!