overload print python


Python Problem Overview

Am I able to overload the print function and call the normal function from within? What I want to do is after a specific line I want print to call my print which will call the normal print and write a copy to file.

Also I don't know how to overload print. I don't know how to do variable length arguments. I'll look it up soon but https://stackoverflow.com/questions/550470/overload-print-python/550477#550477 just told me I can't overload print in 2.x which is what I am using.

Python Solutions

Solution 1 - Python

For those reviewing the previously dated answers, as of version release "Python 2.6" there is a new answer to the original poster's question.

In Python 2.6 and up, you can disable the print statement in favor of the print function, and then override the print function with your own print function:

from __future__ import print_function
# This must be the first statement before other statements.
# You may only put a quoted or triple quoted string, 
# Python comments, other future statements, or blank lines before the __future__ line.

    import __builtin__
except ImportError:
    # Python 3
    import builtins as __builtin__

def print(*args, **kwargs):
    """My custom print() function."""
    # Adding new arguments to the print function signature 
    # is probably a bad idea.
    # Instead consider testing if custom argument keywords
    # are present in kwargs
    __builtin__.print('My overridden print() function!')
    return __builtin__.print(*args, **kwargs)

Of course you'll need to consider that this print function is only module wide at this point. You could choose to override __builtin__.print, but you'll need to save the original __builtin__.print; likely mucking with the __builtin__ namespace.

Solution 2 - Python

Overloading print is a design feature of python 3.0 to address your lack of ability to do so in python 2.x.

However, you can override sys.stdout. (example.) Just assign it to another file-like object that does what you want.

Alternatively, you could just pipe your script through the the unix tee command. python yourscript.py | tee output.txt will print to both stdout and to output.txt, but this will capture all output.

Solution 3 - Python

class MovieDesc:
    name = "Name"
    genders = "Genders"
    country = "Country"

 def __str__(self):
#Do whatever you want here
        return "Name: {0}\tGenders: {1} Country: {2} ".format(self.name,self.genders,self.country)


Solution 4 - Python

I came across the same problem.

How about this:

class writer :
	def __init__(self, *writers) :
		self.writers = writers

	def write(self, text) :
		for w in self.writers :

import sys

saved = sys.stdout
fout = file('out.log', 'w')
sys.stdout = writer(sys.stdout, fout)
print "There you go."
sys.stdout = saved

It worked like a charm for me. It was taken from http://mail.python.org/pipermail/python-list/2003-February/188788.html

Solution 5 - Python

In Python 2.x you can't, because print isn't a function, it's a statement. In Python 3 print is a function, so I suppose it could be overridden (haven't tried it, though).

Solution 6 - Python

Though you can't replace the print keyword (in Python 2.x print is a keyword), it's common practice to replace sys.stdout to do something similar to print overriding; for example, with an instance of StringIO.StringIO. This will capture all of the printed data in the StringIO instance, after which you can manipulate it.

Solution 7 - Python

I answered the same question on a different SO question

Essentially, simplest solution is to just redirect the output to stderr as follows, in the wsgi config file.

sys.stdout = sys.stderr

Solution 8 - Python

just thought I'd add my idea... suited my purposes of being able to run sthg in Eclipse and then run from the (Windows) CLI without getting encoding exceptions with each print statement. Whatever you do don't make EncodingStdout a subclass of class file: the line "self.encoding = encoding" would then result in the encoding attribute being None!

NB one thing I found out during a day grappling with this stuff is that the encoding exception gets raised BEFORE getting to "print" or "write": it is when the parameterised string (i.e. "mondodod %s blah blah %s" % ( "blip", "blap" )) is constructed by... what??? the "framework"?

class EncodingStdout( object ):
    def __init__( self, encoding='utf-8' ):
        self.encoding = encoding
    def write_ln( self, *args ):
        if len( args ) < 2:
            sys.__stdout__.write( args[ 0 ] + '\n' )
            if not isinstance( args[ 0 ], basestring ):
                raise Exception( "first arg was %s, type %s" % ( args[ 0 ], type( args[ 0 ]) ))
            # if the default encoding is UTF-8 don't bother with encoding
            if sys.getdefaultencoding() != 'utf-8':
                encoded_args = [ args[ 0 ] ]
                for i in range( 1, len( args )):
                    # numbers (for example) do not have an attribute "encode"
                    if hasattr( args[ i ], 'encode' ):
                        encoded_args.append( args[ i ].encode( self.encoding, 'replace' ) )
                        encoded_args.append( args[ i ])
                args = encoded_args
            sys.__stdout__.write( args[ 0 ] % tuple( args[ 1 : ] ) + '\n' )
        # write seems to need a flush
    def __getattr__( self, name ):
        return sys.__stdout__.__getattribute__( name )

print "=== A mondodod %s %s" % ( "été", "pluviôse, irritée contre la ville entière" ) 

sys.stdout = EncodingStdout()
sys.stdout.write_ln( "=== B mondodod %s %s", "été", "pluviôse, irritée contre la ville entière" )

# convenience method
def pr( *args ):
    sys.stdout.write_ln( *args )

pr( "=== C mondodod %s %s", "été", "pluviôse, irritée contre la ville entière" )

Solution 9 - Python

For a very simple example, as of Python3.4 (haven't tested with older versions) this works well for me (placed at top of module):

import time
def dprint(string):
  __builtins__.print("%f -- %s" % (time.time(), string))

print = dprint

Note, this only works if the string parameter is a str... YMMV


All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser34537View Question on Stackoverflow
Solution 1 - PythonDevPlayerView Answer on Stackoverflow
Solution 2 - PythonʞɔıuView Answer on Stackoverflow
Solution 3 - PythonYanView Answer on Stackoverflow
Solution 4 - PythonAfrobeardView Answer on Stackoverflow
Solution 5 - PythonJoonas PulakkaView Answer on Stackoverflow
Solution 6 - PythoncdlearyView Answer on Stackoverflow
Solution 7 - PythonlprsdView Answer on Stackoverflow
Solution 8 - Pythonmike rodentView Answer on Stackoverflow
Solution 9 - PythonTroy E. LanesView Answer on Stackoverflow