How to handle both `with open(…)` and `sys.stdout` nicely?

后端 未结 13 748
长发绾君心
长发绾君心 2020-12-07 14:47

Often I need to output data either to file or, if file is not specified, to stdout. I use the following snippet:

if target:
    with open(target, \'w\') as h         


        
13条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-07 15:00

    Okay, if we are getting into one-liner wars, here's:

    (target and open(target, 'w') or sys.stdout).write(content)
    

    I like Jacob's original example as long as context is only written in one place. It would be a problem if you end up re-opening the file for many writes. I think I would just make the decision once at the top of the script and let the system close the file on exit:

    output = target and open(target, 'w') or sys.stdout
    ...
    output.write('thing one\n')
    ...
    output.write('thing two\n')
    

    You could include your own exit handler if you think its more tidy

    import atexit
    
    def cleanup_output():
        global output
        if output is not sys.stdout:
            output.close()
    
    atexit(cleanup_output)
    

提交回复
热议问题