Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cmd and Git bash have a different result when run a Python code

Platform: Git bash MINGW64, Windows 7, 64 CMD When I run a 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 result in CMD and Git bash. When I run it using Git bash, the raw_print() will run first.

When you input 3 answers, then it will show the 4 print in the end. When I run it in CMD, it shows normally, one print, one raw_input().

Can somebody explain it?

EDIT: Actually, my goal is to explain the reason, not to solve this with flush. So It is different with this question

like image 683
naifan Avatar asked Jan 08 '16 03:01

naifan


People also ask

Can you run Python scripts in Git bash?

If you are on Windows and choose to use Git Bash, you'll need to run a few commands to configure it to run Python and Anaconda. We'll do this by creating a . bashrc file.

How do I find my python path in git bash?

Solution: At the command prompt, paste this command export PATH="$PATH:/c/Python36" . That will tell Windows where to find Python.


1 Answers

So I had a look at this and tried a couple of different ways of writing what you have there, and they all acted the same way. Digging into it some more I came across https://code.google.com/p/mintty/issues/detail?id=218. Key from this is andy.koppe's reply:

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 Console prints text to the screen as soon as possible, while mingw (git bash) will wait until the application tells it to update the screen.

So to get it to behave the same in both, you will need to flush the buffer to the screen after each print. How to flush output of Python print? has information about how to do this, but it comes 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 using the -u command, which will stop python from buffering output in mingw.

python -u file.py
like image 74
Mitch Pomery Avatar answered Oct 19 '22 01:10

Mitch Pomery