您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

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

5b51 2022/1/14 8:22:26 python 字数 3599 阅读 561 来源 www.jb51.cc/python

平台: 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

概述

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不同

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 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,%r tall and %r heavy." % (age,weight)

或者你可以使用-u命令在mingw中运行它,这将阻止python缓冲mingw中的输出.

python -u file.py

总结

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


如果您也喜欢它,动动您的小指点个赞吧

除非注明,文章均由 laddyq.com 整理发布,欢迎转载。

转载请注明:
链接:http://laddyq.com
来源:laddyq.com
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。


联系我
置顶