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

# for python3
import sys
with open('file', 'w') as sys.stdout:
    print('test')

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

$ python3 foo.py > file
Answer from moinudin on Stack Overflow
Top answer
1 of 15
582

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

# for python3
import sys
with open('file', 'w') as sys.stdout:
    print('test')

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

$ python3 foo.py > file
2 of 15
290

There is contextlib.redirect_stdout() function in Python 3.4+:

from contextlib import redirect_stdout

with open('help.txt', 'w') as f:
    with redirect_stdout(f):
        print('it now prints to `help.text`')

It is similar to:

import sys
from contextlib import contextmanager

@contextmanager
def redirect_stdout(new_target):
    old_target, sys.stdout = sys.stdout, new_target # replace sys.stdout
    try:
        yield new_target # run some code with the replaced stdout
    finally:
        sys.stdout = old_target # restore to the previous value

that can be used on earlier Python versions. The latter version is not reusable. It can be made one if desired.

It doesn't redirect the stdout at the file descriptors level e.g.:

import os
from contextlib import redirect_stdout

stdout_fd = sys.stdout.fileno()
with open('output.txt', 'w') as f, redirect_stdout(f):
    print('redirected to a file')
    os.write(stdout_fd, b'not redirected')
    os.system('echo this also is not redirected')

b'not redirected' and 'echo this also is not redirected' are not redirected to the output.txt file.

To redirect at the file descriptor level, os.dup2() could be used:

import os
import sys
from contextlib import contextmanager

def fileno(file_or_fd):
    fd = getattr(file_or_fd, 'fileno', lambda: file_or_fd)()
    if not isinstance(fd, int):
        raise ValueError("Expected a file (`.fileno()`) or a file descriptor")
    return fd

@contextmanager
def stdout_redirected(to=os.devnull, stdout=None):
    if stdout is None:
       stdout = sys.stdout

    stdout_fd = fileno(stdout)
    # copy stdout_fd before it is overwritten
    #NOTE: `copied` is inheritable on Windows when duplicating a standard stream
    with os.fdopen(os.dup(stdout_fd), 'wb') as copied: 
        stdout.flush()  # flush library buffers that dup2 knows nothing about
        try:
            os.dup2(fileno(to), stdout_fd)  # $ exec >&to
        except ValueError:  # filename
            with open(to, 'wb') as to_file:
                os.dup2(to_file.fileno(), stdout_fd)  # $ exec > to
        try:
            yield stdout # allow code to be run with the redirected stdout
        finally:
            # restore stdout to its previous value
            #NOTE: dup2 makes stdout_fd inheritable unconditionally
            stdout.flush()
            os.dup2(copied.fileno(), stdout_fd)  # $ exec >&copied

The same example works now if stdout_redirected() is used instead of redirect_stdout():

import os
import sys

stdout_fd = sys.stdout.fileno()
with open('output.txt', 'w') as f, stdout_redirected(f):
    print('redirected to a file')
    os.write(stdout_fd, b'it is redirected now\n')
    os.system('echo this is also redirected')
print('this is goes back to stdout')

The output that previously was printed on stdout now goes to output.txt as long as stdout_redirected() context manager is active.

Note: stdout.flush() does not flush C stdio buffers on Python 3 where I/O is implemented directly on read()/write() system calls. To flush all open C stdio output streams, you could call libc.fflush(None) explicitly if some C extension uses stdio-based I/O:

try:
    import ctypes
    from ctypes.util import find_library
except ImportError:
    libc = None
else:
    try:
        libc = ctypes.cdll.msvcrt # Windows
    except OSError:
        libc = ctypes.cdll.LoadLibrary(find_library('c'))

def flush(stream):
    try:
        libc.fflush(None)
        stream.flush()
    except (AttributeError, ValueError, IOError):
        pass # unsupported

You could use stdout parameter to redirect other streams, not only sys.stdout e.g., to merge sys.stderr and sys.stdout:

def merged_stderr_stdout():  # $ exec 2>&1
    return stdout_redirected(to=sys.stdout, stdout=sys.stderr)

Example:

from __future__ import print_function
import sys

with merged_stderr_stdout():
     print('this is printed on stdout')
     print('this is also printed on stdout', file=sys.stderr)

Note: stdout_redirected() mixes buffered I/O (sys.stdout usually) and unbuffered I/O (operations on file descriptors directly). Beware, there could be buffering issues.

To answer, your edit: you could use python-daemon to daemonize your script and use logging module (as @erikb85 suggested) instead of print statements and merely redirecting stdout for your long-running Python script that you run using nohup now.

Discussions

python - How to redirect stdout to both file and console with scripting? - Stack Overflow
I want to run a python script and capture the output on a text file as well as want to show on console. I want to specify it as a property of the python script itself. NOT to use the command echo " More on stackoverflow.com
🌐 stackoverflow.com
How do I output my print statements to a text file?
if you are doing something like print 'this script is awesome' Then you can use.. $ python myawesomescript.py > textfile.txt or $ python myawesomescript.py >> textfile.txt and it will put the stdout into a file. >> appends data to the end of the file. So if you have a bunch of text in there already it will add it to the end. > overwrites the whole file so it will just contain what you pipe into it. More on reddit.com
🌐 r/learnpython
34
15
January 16, 2014
Is stdout a file?
Terminals actually do have a filename attached to them, and it's pretty easy to find out which one. If you run the tty command, you'll get output like this: /dev/pts/0 That output shows where your terminal's file is located. You can then, for example, echo data to it. So if you open a secondary terminal, you could do echo "Hello!" >/dev/pts/0 and if all goes well, the word "Hello!" will appear on the terminal screen. Data can also be read from the terminal, but doing so from a source that isn't the same terminal messes up the user's ability to type, and doesn't always work well. More on reddit.com
🌐 r/linuxquestions
28
70
December 10, 2019
How to use Popen to Capture Output from a Console Window (Windows OS)?
You need to wrap it and have python communicate any changes using popen.communicate You're currently experiencing the deadlock described here: https://docs.python.org/3/library/subprocess.html#subprocess.Popen.stderr That said for gluing command-line stuff together on windows, you're probably better off using powershell More on reddit.com
🌐 r/learnpython
6
5
April 12, 2024
🌐
Mouse Vs Python
blog.pythonlibrary.org › home › python 101: redirecting stdout
Python 101: Redirecting stdout - Mouse Vs Python
January 31, 2020 - Here we just import Python’s sys module and create a function that we can pass strings that we want to have redirected to a file. We save off a reference to sys.stdout so we can restore it at the end of the function. This can be useful if you intend to use stdout for other things.
🌐
Eli Bendersky
eli.thegreenplace.net › 2015 › redirecting-all-kinds-of-stdout-in-python
Redirecting all kinds of stdout in Python - Eli Bendersky's website
February 20, 2015 - The important take-away from this is: Python and a C extension loaded by it (this is similarly relevant to C code invoked via ctypes) run in the same process, and share the underlying file descriptor for standard output. However, while Python has its own high-level wrapper around it - sys.stdout, the C code uses its own FILE object.
🌐
eSparkBiz
esparkinfo.com › save python screen output to a text file
Save Terminal Output from Python Scripts to a File
January 21, 2026 - Want to store Python output in a file? Use context managers, redirect_stdout, or command-line redirection to easily capture and log your program’s output.
Price   $12
Address   1001 - 1009 10th floor City Center 2, Sukan Mall Cross Road, Science City Rd, 380060, Ahmedabad
🌐
GeeksforGeeks
geeksforgeeks.org › python › ways-to-save-python-terminal-output-to-a-text-file
Ways To Save Python Terminal Output To A Text File - GeeksforGeeks
July 23, 2025 - sys.stdout = f: The print function normally sends output to the terminal, but this line redirects it to the file output.txt.
🌐
DZone
dzone.com › coding › languages › python 101: redirecting stdout
Python 101: Redirecting stdout
June 22, 2016 - here we just import python’s sys module and create a function that we can pass strings that we want to have redirected to a file. we save off a reference to sys.stdout so we can restore it at the end of the function. this can be useful if you intend to use stdout for other things.
Find elsewhere
🌐
Stack Abuse
stackabuse.com › writing-to-a-file-with-pythons-print-function
Writing to a File with Python's print() Function
September 19, 2021 - However, with this method, all ... to a file. It is often more flexible to perform this redirection from within the Python script itself. In Python, the print() function is more flexible than you might think. It was not hard-coded in such a way that specified text can only be written to the display. Instead, it sends text to a location called the standard output stream, also known as stdout...
🌐
Super User
superuser.com › questions › 1154680 › how-do-i-redirect-output-from-python-to-file
windows - How do I redirect output from a Python script to file? - Super User
December 9, 2016 - I want to redirect all output (stdout and stderr) of console to the text file. I make the following steps: Open cmd.exe Start command: "python.exe" > "file.txt" After that, ...
🌐
Python Forum
python-forum.io › thread-41244.html
setting STDOUT and/or STDERR
the script being developed will basically be like a shell script, running many command with some logic between many of them. at the start of the script i want to redirect STDOUT and/or STDERR to output to a specified file, to record all the output f...
🌐
GeeksforGeeks
geeksforgeeks.org › sys-stdout-write-in-python
sys.stdout.write in Python - GeeksforGeeks
April 11, 2025 - import sys import time for i in range(5, 0, -1): sys.stdout.write(f'\rCountdown: {i} ') sys.stdout.flush() time.sleep(1) sys.stdout.write("\nTime's up!\n") # Use double quotes to avoid conflict with the apostrophe ... Finally, we print “Time’s up!” on a new line. To read about more Python's built in methods, refer to Python's Built In Methods · Understanding this difference is important for precise output control, especially in scenarios like dynamic console updates, logging or writing to files.
🌐
Medium
medium.com › xster-tech › python-log-stdout-to-file-e6564a22ffb8
Python Log Stdout to File | by xster | xster | Medium
March 22, 2017 - class MyOutput(): def __init__(self, logfile): self.stdout = sys.stdout self.log = open(logfile, 'w')def write(self, text): self.stdout.write(text) self.log.write(text) self.log.flush()def close(self): self.stdout.close() self.log.close()sys.stdout = MyOutput("log.txt") print "blah blah blah" This class would implement stdout's write and close functions. We then assign the stdout to an instance of this class. Inside the write/close implementations, we also add functionalities to write the texts in a log file as well.
🌐
Reddit
reddit.com › r/learnpython › how do i output my print statements to a text file?
r/learnpython on Reddit: How do I output my print statements to a text file?
January 16, 2014 -

I've got a program that runs and prints statements to the screen that I'd like to output to a file for posterity... I've googled the question, but nothing seems to make sense or help.

A lot of people say to use the write statement, but I keep getting function errors (only takes one, you gave it two).

some people say that you can simply do a >> after the print statement, but how do I know what file that outputs to?

Any advice (spelled out like I'm five) would be greatly appreciated.

🌐
Python documentation
docs.python.org › 3 › tutorial › inputoutput.html
7. Input and Output — Python 3.14.4 documentation
There are several ways to present ... written to a file for future use. This chapter will discuss some of the possibilities. So far we’ve encountered two ways of writing values: expression statements and the print() function. (A third way is using the write() method of file objects; the standard output file can be referenced as sys.stdout...
🌐
Google Groups
groups.google.com › g › comp.lang.python › c › 0lqfVgjkc68
print to screen and file with one print statement
> This redirects all output from Python to the open file. > At the same time I'd like to see all printed text on screen. > How can I do this? ... Either email addresses are anonymous for this group or you need the view member email addresses permission to view the original message ... > Same basic idea: > > #!/usr/bin/env python > > import sys > > class MyWriter: > > def __init__(self, stdout, filename): > self.stdout = stdout > self.logfile = file(filename, 'a') > > def write(self, text): > self.stdout.write(text) > self.logfile.write(text) > > def close(self): > self.stdout.close() > self.logfile.close() > > writer = MyWriter(sys.stdout, 'log.txt') > sys.stdout = writer > > print 'test' >
🌐
AskPython
askpython.com › home › python – stdin, stdout, and stderr
Python - stdin, stdout, and stderr - AskPython
February 16, 2023 - The output is returned via the Standard output (stdout). Standard error – The user program writes error information to this file-handle. Errors are returned via the Standard error (stderr). Python provides us with file-like objects that represent stdin, stdout, and stderr.
🌐
AskPython
askpython.com › home › python – print to file
Python - Print to File - AskPython
February 16, 2023 - vijay@AskPython:~# python output_redirection.py Hi Hello from AskPython exit root@ubuntu:~# cat output.txt Hi Hello from AskPython exit · Usually, when we use the print function, the output gets displayed to the console. But, since the standard output stream is also a handler to a file object, we can route the standard output sys.stdout to point to the destination file instead.