python中print的不换行即时输出解决方案

http://hi.baidu.com/esbat/blog/item/3e811c4ca1a455e1d62afc5a.html

本文原创自esbat的博客,转载请注明出处

python中的print默认是换行的

想要不换行输出有两种办法:

1.print后加上","

############################

>>>print "Hello World",

############################

2.使用sys.stdout.write命令

############################

>>>sys.stdout.write("Hello World")

############################

 

但是,以上的命令在具体执行时,并不会实时显示,每次都是在换行时才把整行指令打出来.

如果要实时显示,需要在每次sys.stdout.write后面加上一行sys.stdout.flush()让屏幕输出

############################

sys.stdout.write("Hello World")

sys.stdout.flush()

sys.stdout.write("one line!")

sys.stdout.flush()

############################

 

附一段我用来控制write换行情况的代码

############################

class ChangeLine:
    NewLine = True

    @classmethod
    def write_out(self,str,typename = 0):
#   0 is "\n.....\n"
        if typename == 0:
            if self.NewLine == False:
                sys.stdout.write('\n')
                sys.stdout.flush()
            sys.stdout.write(str + '\n')
            sys.stdout.flush()
            self.NewLine = True
#   1 is "......."
        if typename == 1:
            sys.stdout.write(str)
            sys.stdout.flush()
            self.NewLine = False
#   2 is "\n......"
        if typename == 2:
            if self.NewLine == False:
                sys.stdout.write('\n')
                sys.stdout.flush()
            sys.stdout.write(str)
            sys.stdout.flush()
            self.NewLine = False
#   3 is "......\n"
        if typename == 3:
            sys.stdout.write(str + '\n')
            sys.stdout.flush()
            self.NewLine = True

############################


你可能感兴趣的:(python)