Question

import select
import sys
inputs=[sys.stdin]
while 1:
    readable,w,e=select.select(inputs,[],inputs)
    for r in readable:
        print 1,
        raw_input()
        print 2
        print 3,

when I tried this python code on Ubuntu, suppose I randomly input sth like 'asd' in the terminate. It shows:

asd
1 2
asd
3 1 2

It seems the behavior of "print blabla," will be influenced by the status of stdin's file descriptor, yet "print blabla" doesn't. Could somebody tell me what is going on there?

Was it helpful?

Solution

As pointed in a comment you are seeing the effects of line buffered standard output in Python 2.x: a trailing , in a print will prevent it to emit a new line. The text with the trailing , will not be printed before a new line is emited. You can remove the buffering with some simple code:

#!/usr/bin/env python
import sys
class Logger(object):
    def __init__(self, stream):
        self.stream = stream

    def write(self, msg):
        self.stream.write(msg)

    def flush(self):
        pass

if __name__ == '__main__':
    sys.stdout = Logger(sys.stdout)
    print 'User says hello!',
    print 'Goodbye, cruel world!'

As you see sys.stdout is replaced with other stream which does a flush after every print. You can also see this thread and this one for more information.

OTHER TIPS

there is a difference between print xxxxxx to print xxxxxx,

print "Yes"

will print Yes to the screen and add \n (newline)

print "Yes",

will print print Yes to the screen without \n (newline)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top