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

时间:2016-02-12 18:48:34

标签: python file python-3.x stdout

因为我已经了解了这个模式,所以我一直在使用

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

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

2 个答案:

答案 0 :(得分:5)

is this a pattern I should be using?

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)

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.)

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).

EDIT:

From the 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.

答案 1 :(得分:0)

This question, about how to do exactly what you've been doing has quite a few comments and answers about the drawbacks of redirecting stdout, especially this comment to one of the answers:

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