Cmd and Git bash have different result when running Python code

Platform: Git bash MINGW64, Windows 7, 64 CMD When I run Python code from Learn Python The Hard Way ex11 . The code is simple.

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) 

But they have different results in CMD and Git bash. When I run it using Git bash, raw_print () is started first.

When you enter 3 answers, then at the end 4 seals will be displayed. When I run it in CMD, it shows normally, one output, one raw_input() .

Can someone explain this?

EDIT: Actually, my goal is to explain the reason, and not solve this problem with a flash. So this is different from this question.

+5
source share
1 answer

So, I looked at this and tried several different ways to write what you have, and they all worked the same way. Delving into it yet, I came across https://code.google.com/p/mintty/issues/detail?id=218 . The key to this is andy.koppe's answer:

The key to the problem is that the default buffering mode stdout depends on the type of device: console unbuffered, channel buffered. This means that in the console, the output will be displayed immediately, whereas in mintty it will appear only after the buffer is full or turns red, as it happens at the end of main ().

The Windows console prints the text on the screen as soon as possible, while mingw (git bash) will wait until the application informs it of the screen update.

So, to make yourself behave the same in both cases, you will need to flush the buffer on the screen after each print. How to clear Python print output? contains information on how to do this, but it boils down to the following:

 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) 

Alternatively, you can run it in mingw with the -u command, which will stop python output from buffering in mingw.

 python -u file.py 
+8
source

Source: https://habr.com/ru/post/1240139/


All Articles