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
- MultiWriter Class: This class wraps your target file and the standard console output. Its
write()method is called automatically byprint()whenever you pass it as thefileargument. - Dual Output: Every time
print()sends text todual_writer, thewrite()method forwards that text to both the file and the console—including the automatic newline thatprint()adds by default. - Clean Resource Handling: Using a
withstatement 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 theprint()function as requested. - Minimal overhead: The custom class is lightweight and reusable for any number of
print()calls.
内容的提问来源于stack exchange,提问作者Becay
相关产品推荐
相关产品推荐

