0

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?

3
  • You never showed us the printing code, so we have no idea what the bug can be. Commented May 13, 2012 at 12:59
  • sorry for the miss..edited the code accordingly.. Commented May 13, 2012 at 13:04
  • 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" Commented May 13, 2012 at 13:15

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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) 

...

2 Comments

thanks a lot guys.i was trying to remove the '\n' from buffer .anyway this works..
this fails when there are two print statements.We have to handle that also.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.