I am using python 2.6.6 and I need to overload the default python print function. I need to do it because this code may be used on a system where a built-in function has to be used to generate output, otherwise no output is displayed.
So, just for example, if you have a python script like this:
from __future__ import print_function
def NewPrint(Str):
with open("somefile.txt","a") as AFile:
AFile.write(Str)
def OverloadPrint():
global print
print = NewPrint
OverloadPrint()
print("ha")
It works fine. The input to the "overloaded" print is in the file specified by NewPrint.
Now with that in mind I would like to be able to run the couple of lines above and have print to do what NewPrint does during the entire execution of the script. Right now if I call a function from another module that uses print it will use the built-in print and not the one I just overwrote. I guess this has something to do with namespaces and built-ins, but my python is not good enough.
Edit:
I tried to keep simple, but looks like this caused more confusion...
- The function that overloads print will print to a GUI, so no need to care about redirection IF the function is overloaded.
I know my example does not do what the print function actually does. A better example of how I am thinking of coding it is (still not great I know):
def hli_print(*args, **kw): """ print([object, ...], sep=' ', end='\n', file=sys.stdout) """ sep = kw.get('sep', ' ') end = kw.get('end', '\n') File = kw.get('file', sys.stdout) args = [str(arg) for arg in args] string = sep.join(args) + end File.write(string) hli_Print(string)
From 2 above you can see the function I have to use to print to the GUI "hli_Print" it is a C++ function exposed through a swig wrapper.
- We only use the standard library and our own swig wrappers, also our developers use print as a function (getting used to 3.X). So I did not really worry much about some other module calling print and having something else instead.
From all the comments I guess that just using some print_() function instead of print() (which is what we currently do) may be the best, but I got really curious to see if in python it would be possible to do what I described.