2

Simple question, I would like to append text to the front of every print I call, for example if I set the text to hello and ran this:

print 'hello there'
print ' hi again'

It would print this:

hellohello there
hello hi again

Is there any way of doing this, without using a function to use that instead of print?

user1447941
  • 3,675
  • 10
  • 29
  • 34
  • "stylize the printing" not sure I understand this part, could you please rephrase? – Levon Jun 12 '12 at 23:19
  • I meant creating a function that just called `print 'hello' + message`, I would like to edit the actual `print` command. – user1447941 Jun 12 '12 at 23:21
  • 2
    Why do you want to avoid making a function for this? Something like `def myPrint(text): print('hello '+text`) is really the way to go for this. – Junuxx Jun 12 '12 at 23:29
  • @Junuxx - Because I would _prefer_ to use `print` instead of another function to print. – user1447941 Jun 12 '12 at 23:37
  • 2
    @user1447941: I've used function names like 'log()' or 'say()' in similar situations. While people may offer you hackish solutions to redefine `print`, I would really advise you not to do that. It's only going to cause problems and confusions later on. – Junuxx Jun 12 '12 at 23:51

3 Answers3

3

You could override print as per DevPlayer's post here on StackOverflow, slightly modified here:

from __future__ import print_function
# Note: If you are using Python 3 leave this line out
# This must be the first statement before other statements.
# You may only put a quoted or triple quoted string, 
# Python comments or blank lines before the __future__ line.
import sys

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
    sys.stdout.write('hello')
    return __builtins__.print(*args, **kwargs)

print ("hello there")
print (" hi again")

[Edit] ...or as DSM suggests, you could avoid the sys call with this:

from __future__ import print_function
# Note: If you are using Python 3 leave this line out
# This must be the first statement before other statements.
# You may only put a quoted or triple quoted string, 
# Python comments or blank lines before the __future__ line.

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
    __builtins__.print('hello',end='')
    return __builtins__.print(*args, **kwargs)

print ("hello there")
print (" hi again")
Community
  • 1
  • 1
Jon Cage
  • 36,366
  • 38
  • 137
  • 215
1

You can't change Python 2's print statement, but you can write your own file-like object and use it:

class PrefixedFile(object):
    def __init__(self, f, prefix):
        self.f = f
        self.prefix = prefix

    def write(self, s):
        s = s.replace("\n", "\n"+self.prefix)
        self.f.write(s)

sys.stdout = PrefixedFile(sys.stdout, "hello: ")

print "One"
print "Two"

Note this code doesn't quite work because it missing a prefix on the very first line, and adds one at the very end, but you get the idea! :)

Ned Batchelder
  • 364,293
  • 75
  • 561
  • 662
  • 1
    @JonCage: You can change the print *function*, but changing the print *statement* is not easily done. – Eric O. Lebigot Jun 12 '12 at 23:38
  • 1
    Yeah, okay, you got me there :-) – Jon Cage Jun 12 '12 at 23:42
  • @Ned: Do you know what the community recommends, when it comes to replacing `sys.stdout`? `print` behaves behind the scenes, in a non-explicit way, when `sys.stdout` is replaced… I tend to prefer introducing my own print function instead of replacing `sys.stdout`, or maybe use the logging module, if appropriate. I would only replace `sys.stdout` as an afterthought. – Eric O. Lebigot Jun 12 '12 at 23:42
  • 3
    I agree that replacing sys.stdout is a blunt instrument, and better would be to use the logging module or a custom print-like function. – Ned Batchelder Jun 13 '12 at 00:37
0

Even though Jon Cage's answer is a good way of replacing the print() function, I would advise to instead use your own print function (using Jon's code):

from __future__ import print_function
# Note: If you are using Python 3 leave this line out
# This must be the first statement before other statements.
# You may only put a quoted or triple quoted string, 
# Python comments or blank lines before the __future__ line.

def my_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
    print('hello', end='')
    print(*args, **kwargs)

The only difference with Jon's answer is that you do not override the built-in print() ("monkey patching"). I advocate this instead of modifying print() because this makes your code more maintainable, as everybody expects print() to be the built-in one.

Using the print() function instead of the print statement, in my_print(), gives greater flexibility.

Eric O. Lebigot
  • 91,433
  • 48
  • 218
  • 260
  • I agree that using a differently named function is much safer, but that's not what the OP asked for ;-) – Jon Cage Jun 12 '12 at 23:38
  • @JonCage: Yeah, he asked for a replacement of the print *statement*, and none of the answers offers this, because this is hard. :) – Eric O. Lebigot Jun 12 '12 at 23:44