Redirect stdout to a file in Python?

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

    Quoted from PEP 343 -- The "with" Statement (added import statement):

    Redirect stdout temporarily:

    import sys
    from contextlib import contextmanager
    @contextmanager
    def stdout_redirected(new_stdout):
        save_stdout = sys.stdout
        sys.stdout = new_stdout
        try:
            yield None
        finally:
            sys.stdout = save_stdout
    

    Used as follows:

    with open(filename, "w") as f:
        with stdout_redirected(f):
            print "Hello world"
    

    This isn't thread-safe, of course, but neither is doing this same dance manually. In single-threaded programs (for example in scripts) it is a popular way of doing things.

提交回复
热议问题