平台:
Git bash MINGW64,Windows 7,64 CMD
当我从 Learn Python The Hard Way ex11运行Python代码时.代码很简单.
当我从 Learn Python The Hard Way ex11运行Python代码时.代码很简单.
print "How old are you?",age = raw_input() print "How tall are you?",height = raw_input() print "How much do you weigh?",weight = raw_input() print "So,you're %r old,%r tall and %r heavy." % ( age,height,weight)
但是他们在CMD和Git bash中有不同的结果.当我使用Git bash运行它时,raw_print()将首先运行.
当您输入3个答案时,它将在最后显示4个打印件.当我在CMD中运行它时,它通常显示一个print,一个raw_input().
有人可以解释一下吗?
编辑:实际上,我的目标是解释原因,而不是用flush来解决这个问题.所以与this question不同
解决方法
所以我看了一下这个并尝试了几种不同的方式来编写你所拥有的东西,他们都采取了同样的方式.我进入了更多,我遇到了
https://code.google.com/p/mintty/issues/detail?id=218.关键在于andy.koppe的回复:
The key to the problem is that stdout’s default buffering mode depends on the type of device: unbuffered for a console,buffered for a pipe. This means that in a console the output will appear immediately,whereas in mintty it will only appear once the buffer is either full or flushed,as happens at the end of main().
Windows控制台尽快将文本打印到屏幕上,而mingw(git bash)将等到应用程序告诉它更新屏幕.
因此,要使它在两者中表现相同,您需要在每次打印后将缓冲区刷新到屏幕. How to flush output of Python print?有关于如何执行此操作的信息,但它归结为以下内容:
import sys print "How old are you?" sys.stdout.flush() age = raw_input() print "How tall are you?" sys.stdout.flush() height = raw_input() print "How much do you weigh?" sys.stdout.flush() weight = raw_input() print "So,%r tall and %r heavy." % (age,weight)
或者你可以使用-u命令在mingw中运行它,这将阻止python缓冲mingw中的输出.
python -u file.py