You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中使用print语句file属性时同时输出内容到控制台的技术问询

Solution: Print to Both File and Console with a Single print() Call

Nice question! I’ve run into this exact scenario before—wanting to log output to a file while still seeing it in the console without repeating the same string twice in separate print() calls. Here’s how to do it strictly using print() and avoiding redundant code:

The Core Idea

The print() function’s file parameter accepts any object that has a write() method (not just actual file objects). We can leverage this by creating a custom "writer" class that sends text to both your target file and the console (sys.stdout) at the same time.

Full Code Example

import sys

class MultiWriter:
    def __init__(self, target_file):
        self.target_file = target_file
        self.console = sys.stdout

    def write(self, text):
        # Write to the file first
        self.target_file.write(text)
        # Then write to the console
        self.console.write(text)

# Usage
with open('output.txt', 'w') as out_file:
    # Create our multi-writer instance
    dual_writer = MultiWriter(out_file)
    
    # Now use print() normally, just pass the dual_writer to the file parameter
    print('Hello World!', file=dual_writer)
    print('This line goes to both file and console', file=dual_writer)
    print('No repeated strings needed!', file=dual_writer)

How It Works

  1. MultiWriter Class: This class wraps your target file and the standard console output. Its write() method is called automatically by print() whenever you pass it as the file argument.
  2. Dual Output: Every time print() sends text to dual_writer, the write() method forwards that text to both the file and the console—including the automatic newline that print() adds by default.
  3. Clean Resource Handling: Using a with statement ensures the output file is properly closed when you’re done, so you don’t have to worry about manual cleanup.

Why This Fits Your Requirements

  • No repeating strings: You only write your message once per print() call.
  • Strictly uses print(): All output is handled through the print() function as requested.
  • Minimal overhead: The custom class is lightweight and reusable for any number of print() calls.

内容的提问来源于stack exchange,提问作者Becay

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 11:43:10