您的位置:首页 > 编程语言 > Python开发

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

2014-05-15 13:18 746 查看
本文原创自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
############################
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息