You could have your add_string
function overwrite the builtin print
function:
from __future__ import print_function # for python 2.x
def add_string(prefix):
def print_with_prefix(*args, **kwargs):
if prefix:
args = (prefix,) + args
__builtins__.print(*args, **kwargs)
global print
print = print_with_prefix
You can set or unset the prefix while preserving any other arguments passed to print
.
print("foo") # prints 'foo'
add_string(">>>")
print("bar") # prints '>>> bar'
print("bar", "42", sep=' + ', end="###\n") # prints '>>> + bar + 42###'
add_string(None)
print("blub") # prints 'blub'
If you are using the print
statement (i.e. print "foo"
instead of print("foo")
) then you have to redefine sys.stdout
with a custom writer:
import sys
stdout = sys.stdout
def add_string(prefix):
class MyPrint:
def write(self, text):
stdout.write((prefix + text) if text.strip() else text)
sys.stdout = MyPrint() if prefix else stdout