Redirect stdout to a file in Python?

后端 未结 10 1350
轻奢々
轻奢々 2020-11-21 05:26

How do I redirect stdout to an arbitrary file in Python?

When a long-running Python script (e.g, web application) is started from within the ssh session and backgoun

10条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2020-11-21 05:42

    If you want to do the redirection within the Python script, setting sys.stdout to a file object does the trick:

    import sys
    sys.stdout = open('file', 'w')
    print('test')
    

    A far more common method is to use shell redirection when executing (same on Windows and Linux):

    $ python foo.py > file
    

提交回复
热议问题