深度阅读

How to redirect stdout to a file in Python?

作者
作者
2023年08月22日
更新时间
14.46 分钟
阅读时间
0
阅读量

To redirect stdout to a file in Python, you can use the sys module and the stdout attribute, along with the open() function to create a file. Here’s an example:

import sys

# Open a file for writing
with open('output.txt', 'w') as file:
    # Save the current value of stdout
    original_stdout = sys.stdout
    # Redirect stdout to the file
    sys.stdout = file

    # Print to stdout
    print('Hello, world!')

    # Reset stdout to its original value
    sys.stdout = original_stdout

In this example, we create a file named “output.txt” using the open() function. We then save the current value of sys.stdout, which is the standard output stream, to a variable named original_stdout. Next, we set sys.stdout to be the file object we just created. This redirects any subsequent calls to print() to write to the file instead of the console.

We then print “Hello, world!” using print(). This will write to the file instead of the console.

Finally, we reset sys.stdout to its original value. This ensures that any subsequent output will again be written to the console.

Note that this method only works for output that originates from the print() statement or any other calls to sys.stdout. If you want to redirect all output, including output that comes from Python’s built-in input() function, you can use the subprocess module to launch the Python interpreter with a new input/output stream.

相关标签

博客作者

热爱技术,乐于分享,持续学习。专注于Web开发、系统架构设计和人工智能领域。