运行Python代码时,Cmd和Git bash有不同的结果

运行Python代码时,Cmd和Git bash有不同的结果,第1张

概述平台: 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 d 平台: 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中运行它时,它通常显示一个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 sysprint "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
总结

以上是内存溢出为你收集整理的运行Python代码时,Cmd和Git bash有不同的结果全部内容,希望文章能够帮你解决运行Python代码时,Cmd和Git bash有不同的结果所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/1206742.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-04
下一篇 2022-06-04

发表评论

登录后才能评论

评论列表(0条)

保存