【问题标题】:Cmd and Git bash have a different result when run a Python code运行 Python 代码时 Cmd 和 Git bash 有不同的结果
【发布时间】:2016-01-08 03:20:18
【问题描述】:

平台:Git bash MINGW64、Windows 7、64 CMD 当我从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中运行它时,它正常显示,一个打印,一个raw_input()

谁能解释一下?

编辑:实际上,我的目标是解释原因,而不是用flush解决这个问题。所以它与this question不同

【问题讨论】:

  • @KevinGuan 我已经编辑过了。实际上,我的目标是解释原因,而不是用flush解决这个问题。所以这与另一个问题不同。回答者 MitchPomery 的缓冲模式是关键。

标签: python windows bash cmd


【解决方案1】:

所以我看了一下这个并尝试了几种不同的方式来写你那里的内容,它们都以相同的方式行事。深入研究它,我遇到了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 中运行它,这将阻止 python 在 mingw 中缓冲输出。

python -u file.py

【讨论】:

  • -u 标志确实对我有用:不需要额外的代码。
猜你喜欢
  • 2012-02-23
  • 1970-01-01
  • 2014-07-14
  • 1970-01-01
  • 1970-01-01
  • 2018-11-18
  • 2021-09-22
  • 2019-02-28
  • 2021-01-20
相关资源
最近更新 更多