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

后端 未结 13 784
长发绾君心
长发绾君心 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 14:52

    How about opening a new fd for sys.stdout? This way you won't have any problems closing it:

    if not target:
        target = "/dev/stdout"
    with open(target, 'w') as f:
        f.write(content)
    

提交回复
热议问题