Python version of freopen()

后端 未结 5 1544
借酒劲吻你
借酒劲吻你 2020-12-29 10:58

Is there anything in python that can replicate the functionality of freopen() in C or C++? To be precise, I want to replicate the functionality of:

freopen(\         


        
5条回答
  •  没有蜡笔的小新
    2020-12-29 11:38

    sys.stdout is simply file object, so, you can reopen it to another destination

    out = sys.stdout
    sys.stdout = open('output.txt', 'w')
    // do some work
    sys.stdout = out
    

    out is only for recovering sys.stdout destination to default after work (as suggested Martijn Pieters - you can recover it by using sys.__stdout__, or not recover at all, if you don't need it).

提交回复
热议问题