문제

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?

도움이 되었습니까?

해결책

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.

다른 팁

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)

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top