2016-01-08 15 views
5

平臺:Git bash MINGW64,Windows 7,64 CMD 當我從Learn Python The Hard Way ex11運行Python代碼時。代碼很簡單。當運行Python代碼時,Cmd和Git bash有不同的結果

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中運行它時,它通常顯示一個打印,一個raw_input()

有人可以解釋嗎?

編輯:其實我的目標是解釋原因,而不是用flush來解決這個問題。所以它與this question不一樣

+0

【如何刷新蟒紋的輸出?](http://stackoverflow.com/questions/230751/how-to-flush-output-of-python-print) –

+1

@KevinGuan我的可能的複製已編輯它。其實,我的目標是解釋原因,而不是用沖水來解決這個問題。所以它與另一個問題是不同的。來自回答者MitchPomery的緩衝模式擊中了關鍵。 – naifan

回答

8

所以我看了一下這個,試着用幾種不同的方式來寫你在那裏的東西,他們都以相同的方式行事。深入挖掘,我遇到了https://code.google.com/p/mintty/issues/detail?id=218。這裏的關鍵是andy.koppe的回覆:

問題的關鍵是stdout的默認緩衝模式取決於設備的類型:無緩衝的控制檯,管道緩衝。這意味着在控制檯中,輸出將立即顯示,而在mintty中,只有在緩衝區已滿或刷新後纔會出現,如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, you're %r old, %r tall and %r heavy." % (age, height, weight) 

另外,您可以使用-u命令,這將在MinGW的緩衝輸出停止蟒蛇在MinGW的運行。

python -u file.py 
+2

Thx。它已經解決了我的問題。緩衝模式。 – naifan

相關問題