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

后端 未结 13 750
长发绾君心
长发绾君心 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:58

    Another possible solution: do not try to avoid the context manager exit method, just duplicate stdout.

    with (os.fdopen(os.dup(sys.stdout.fileno()), 'w')
          if target == '-'
          else open(target, 'w')) as f:
          f.write("Foo")
    

提交回复
热议问题