【问题标题】:Print updating variable in the same line [duplicate]在同一行中打印更新变量[重复]
【发布时间】:2017-05-30 15:49:26
【问题描述】:

我要编写的代码非常简单:

我想打印一个迭代变量,但我不想为每个循环打印所有行,我希望它会更新前一个。

例子:

for i in range(0,2000):
   print 'number is %d', %i 

错误的结果:

number is 0
number is 1
number is 2
number is 3
number is 4
number is 5
number is 6
...
...

我想要的是:

number is 0 

在第二次迭代中:

number is 1 `(it will replace 0 and I don't want the previous 0 anymore).`

这将类似于仅在一行中更新某些内容的百分比。

在 Python 中是否存在用于它的函数?

【问题讨论】:

  • 仅供参考:您使用 # 在 python 中编写 cmets

标签: python


【解决方案1】:

这样就可以了,并且每 1 秒更新一次:

import sys
import time

for i in range(0,2000):
    sys.stdout.write('\rnumber is %d' %i)
    sys.stdout.flush()
    time.sleep(1)

【讨论】:

    【解决方案2】:

    您可以在清除终端时尝试this 线程中的某些内容,或者fuglede 发布的重复内容中的某些内容。

    以下代码在 Mac 中对我来说运行良好,但如果你删除 time.sleep(),它会运行得如此之快,以至于你甚至看不到打印。

    import time, sys
    
    for i in range(0, 20):
        print 'Number is: %d' % i
        time.sleep(.1)
        sys.stderr.write("\x1b[2J\x1b[H")
    

    【讨论】:

      【解决方案3】:

      你想要的叫做Carriage Return,或者\r

      用途:

      for i in range(0,2000):
          print "number is %d       \r" %i,
      

      空格将使行从先前的输出中保持清晰。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-08-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-07-12
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多