0
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?

2 Answers2

0

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)

Kobi K
  • 7,743
  • 6
  • 42
  • 86
  • Thank you. But could you explain why 3 will not present until I make the next input? – user2837543 Oct 02 '13 at 07:12
  • 1
    @user2837543 you can check [this question for more](http://stackoverflow.com/questions/4009672/python-trailing-comma-after-print-executes-next-instruction) – Leon Young Oct 02 '13 at 07:18
  • @user2837543 can you edit the post output so it will be clear what is input and what is output. you can use >>> for input – Kobi K Oct 02 '13 at 07:38
0

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.

Community
  • 1
  • 1
Vicent
  • 5,322
  • 2
  • 28
  • 36