Rilwan
Rilwan

Reputation: 2301

Python: modify builtin print functionality

I want to customize the print statement in Python for additional text. But with my approach, it seems that the Enter key is getting buffered in the input.

The program I used is:

class rename_print:
    def __init__(self, stdout):
        self.stdout = stdout     
    def write(self, text):
        self.stdout.write('###' + text)     
        self.stdout.flush()
    def close(self):
        self.stdout.close()

import sys

prints = rename_print(sys.stdout)
sys.stdout = prints
print 'abc'

The output I get is

###abc###

The output I expected is

###abc

What might be the reason of this? I doubt that input stream is getting buffered with the Enter key. How can I solve this issue?

Upvotes: 0

Views: 836

Answers (2)

Jay M
Jay M

Reputation: 4297

I think what is happening is that print implicitly adds a newline. This extra print is also calling your redirected write function so you get another "###\n"

It's a bit hacky, but try this:

...

def write(self, text):
    if text!="\n":
       self.stdout.write('###' + text)

...

Upvotes: 1

mata
mata

Reputation: 69042

print writes a newline character to the output stream per default (or a space between each argument). so you get two calls to write, one with "abc" and one with "\n".

so if you don't want that behaviour, you have to treat that calls separately.

Upvotes: 2

Related Questions