Reputation: 305
I need to customize the print()
, so that it does something else besides printing what I want. Is there a way to override it?
Upvotes: 2
Views: 1704
Reputation: 113
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
Upvotes: 5
Reputation: 1934
DEBUG=1 # only print when debugging
import datetime
_print = print # preserve original
def print(*args, **kwargs):
if DEBUG:
_print(f"{datetime.datetime.now()} ", end='')
_print(*args, **kwargs)
else:
pass
# ---- regular print usage
print("abc", x, y, z)
Got the idea from here: https://stackoverflow.com/a/70915521/2612429
Upvotes: 0
Reputation: 46869
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')
Upvotes: 1
Reputation: 202
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)
Upvotes: 0