pythonprinting

How to override the builtin method "print()"


I need to customize the print(), so that it does something else besides printing what I want. Is there a way to override it?


Solution

  • one option is to use contextlib.redirect_stdout:

    from contextlib import redirect_stdout
    
    with open('file.txt', 'a') as file, redirect_stdout(file):
        print('hello')
    

    if you need both printing and saving to a file, this may work:

    from contextlib import redirect_stdout
    from sys import stdout
    from io import StringIO
    
    class MyOutput(StringIO):
        def __init__(self, file):
            super().__init__()
            self.file = file
    
        def write(self, msg):
            stdout.write(msg)
            self.file.write(msg)
    
    with open('file.txt', 'a') as file, redirect_stdout(MyOutput(file=file)):
        print('hello')