ITPub博客

首页 > 应用开发 > > python_print函数的flush参数

python_print函数的flush参数

作者:tony0087 时间:2019-09-10 16:24:18 0 删除 编辑

今天发现了一个奇怪的现象,直接上代码

import sys
from colorama import Fore, Back, Style 

def print_example():
    print(Fore.RED+ "1. This is the first sentence")
     long_str=' Blowing in the wind'
    print(Fore.WHITE + '2. long_str =', end='')
    #print('2. long_str= ', end='')
    print( long_str,file=sys.stderr)
    print(Fore.CYAN + "3. Do they printed in right order")

print_example()

打印出来的结果并不是我设想的顺序

1. This is the first sentence
 Blowing in the wind
2. long_str =3. Do they printed in right order

为什么stderr和stdout会打印到一起呢? 我的猜想也许跟stdout, stderr的缓冲机制有关 后来发现python 3.3 后print可以加flush参数, 这样就能得到我想要的打印次序

import sys 
    from colorama import Fore, Back, Style
    def print_example(): 
        print(Fore.RED+ "1. This is the first sentence") 
         long_str=' Blowing in the wind' 
        print(Fore.WHITE + '2. long_str =', end='',flush=True) 
        #print('2. long_str= ', end='') 
        print( long_str,file=sys.stderr) 
        print(Fore.CYAN + "3. Do they printed in right order") 
    print_example() 
    打印出来如下
    1. This is the first sentence
    2. long_str = Blowing in the wind
    3. Do they printed in right order


来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/1747/viewspace-3147747/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2019-09-06

  • 博文量
    233
  • 访问量
    9714