Redirect stdout to a file in Python?

后端 未结 10 1347
轻奢々
轻奢々 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:56

    The other answers didn't cover the case where you want forked processes to share your new stdout.

    To do that:

    from os import open, close, dup, O_WRONLY
    
    old = dup(1)
    close(1)
    open("file", O_WRONLY) # should open on 1
    
    ..... do stuff and then restore
    
    close(1)
    dup(old) # should dup to 1
    close(old) # get rid of left overs
    

提交回复
热议问题