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


点击(此处)折叠或打开

  1. import sys
  2. from colorama import Fore, Back, Style

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

  10. print_example()

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

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

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


点击(此处)折叠或打开

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

最后附上参考资料如何使用python打印彩色

Print Colors in Python terminal

09-26 17:43
查看更多