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

- 305
- 1
- 6
-
`def my_print(*args): ...; print = my_print`. but why would you want to do that? – hiro protagonist Aug 05 '22 at 12:57
-
I don't think it works like this – Omar Yacop Aug 05 '22 at 12:57
-
What exactly do you want to achieve? – fsimonjetz Aug 05 '22 at 12:58
-
just add anything I print to a file.txt that I will give the path to it – Omar Yacop Aug 05 '22 at 12:58
-
1that is what [`logging`](https://docs.python.org/3/library/logging.html#module-logging) is for... – hiro protagonist Aug 05 '22 at 12:59
-
can you explain more @hiroprotagonist – Omar Yacop Aug 05 '22 at 13:00
-
Does this answer your question? [Redirect stdout to a file in Python?](https://stackoverflow.com/questions/4675728/redirect-stdout-to-a-file-in-python) – Filip Müller Aug 05 '22 at 13:11
-
It does @FilipMüller but I also want to print it – Omar Yacop Aug 05 '22 at 13:20
-
And why do you need to override `print`? Why don't you just create a new function that calls `print` inside? – Filip Müller Aug 05 '22 at 13:21
-
there are a lot of printing, so I am not into creating a custom function if there is a way to override print – Omar Yacop Aug 05 '22 at 13:23
-
2`python myscript.py | tee logfile.txt`. No change to the script needed. – chepner Aug 05 '22 at 14:08
3 Answers
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

- 93
- 6
-
-
`from __future__ import print_function` is only required in python 2. in python 3 there is no need for that. – hiro protagonist Aug 05 '22 at 13:33
-
Hiro, I did it for Python 2 And Python 3 Both, For The Ease of Omar! – Ganime Dewer Aug 05 '22 at 16:07
-
i hope people have stopped using python 2 nowadays... but ok, +1. – hiro protagonist Aug 05 '22 at 16:35
-
-
i was not criticizing your answer as not helpful! that was more a comment in general than about your answer. sorry if you feel offended... – hiro protagonist Aug 06 '22 at 06:46
-
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')

- 44,693
- 14
- 86
- 111
-
okay, but I am not into creating a local method for this. I would just do it with print, without the need of contextlib – Omar Yacop Aug 05 '22 at 13:09
-
you are creating a local method in the accepted answer... this here does not create a function - it creates a context and within that context all `print` statemements (and everything that writes to `sys.stdout`) is redirected. imho this is cleaner than the accepted answer. – hiro protagonist Aug 05 '22 at 13:31
-
-
-
so intead of print("hello") it will be print(statement) where statement will be a paramter – Omar Yacop Aug 05 '22 at 13:35
-
-
-
no. you do that **once** at the beginning of your program and call your functions inside that context. and you *can* do both: print and safe. you'd need to write some additional code for that. – hiro protagonist Aug 05 '22 at 13:39
-
oh you mean I will replace print("Hello") with my main function, right? – Omar Yacop Aug 05 '22 at 13:40
-
-
-
your answer isn't working, it either saves the print, or print without saving,. – Omar Yacop Aug 05 '22 at 13:56
-
as i said, you need to add some more code. i added an example. – hiro protagonist Aug 05 '22 at 13:59
-
-
that is just the type checker. it would have run anyway. but i fixed it in order so silence the type checker. maybe this could have been done in a cleverer way? – hiro protagonist Aug 05 '22 at 14:36
-
one thing is that it only get what is written inside the with block, and not any functions inside it, say if a function prints something, it will not get what this function prints – Omar Yacop Aug 05 '22 at 14:41
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)

- 202
- 2
- 7