0

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

Omar Yacop
  • 305
  • 1
  • 6

3 Answers3

3

Here is A Page That Will Help You With Overriding Functions!

Here is A Way To Override print! (Making a New print)

Code:

from __future__ import print_function

try:
    import __builtin__
except ImportError:
    import builtins as __builtin__

def print(*args, **kwargs):
    """My custom print() function."""
    __builtin__.print('your text')
    return __builtin__.print(*args, **kwargs)

print()

Output: your text

The Line __builtin__.print('your text') would Print 'Your Text', you can put other function Also Instead of Print, it would Print Your Given Text also As The Return Line Says It to, it used the built in print function!

The Second Thing That you can Do is That You Can Remove The Return Line so The Function wouldn't Print Anything To The Console

Hope This Helps

1

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')
hiro protagonist
  • 44,693
  • 14
  • 86
  • 111
0

You can override the print() method but you have to create class and then override the "str" dunder method (print() uses "str" implementation in backend). Here is the code.

a = 2
print(a)

class abc:
    def __init__(self,x):
        self.x = x
    def __str__(self):
        return "The value is " + str(self.x)

a = abc(2)
print(a)
Mujtaba Mateen
  • 202
  • 2
  • 7