Python capture all printed output

前端 未结 1 1186
被撕碎了的回忆
被撕碎了的回忆 2021-02-13 13:32

I am looking to write console based programs in python that can execute functions to perform generic tasks, pretty generic. Is it possible to capture everything written to the c

相关标签:
1条回答
  • 2021-02-13 14:02

    You can do this by setting sys.stdout to be a file of your choice

    import sys
    
    sys.stdout = open('out.dat', 'w')
    print "Hello"
    
    sys.stdout.close()
    

    Will not display any output but will create a file called out.dat with the printed text.

    Note that this doesn't need to be an actual file but could be a StringIO instance, which you can just use the getvalue method of to access everything that has been printed previously.

    0 讨论(0)
提交回复
热议问题