【问题标题】:'Waiting' animation in command prompt (Python)命令提示符中的“等待”动画(Python)
【发布时间】:2011-10-25 17:31:29
【问题描述】:

我有一个 Python 脚本需要很长时间才能运行。我非常希望命令行输出有一点“等待”动画,就像我们在浏览器中为 AJAX 请求获得的漩涡一样。类似于 '\' 的输出,然后将其替换为 '|',然后是 '/',然后是 '-'、'|' 等,就像文本在循环中一样。我不确定如何在 Python 中替换之前打印的文本。

【问题讨论】:

    标签: python animation command


    【解决方案1】:

    使用\r 和不带换行符的打印(即带逗号的后缀):

    animation = "|/-\\"
    idx = 0
    while thing_not_complete():
        print(animation[idx % len(animation)], end="\r")
        idx += 1
        time.sleep(0.1)
    

    对于 Python 2,使用 print 语法:

    print animation[idx % len(animation)] + "\r",
    

    【讨论】:

    • 非常适合我(将 'thing_not_complete()' 更改为 'True' 时),非常棒的小动画!
    • Here 是预先烘焙好的东西。
    • Python 3 在打印行中会发生什么变化?
    • @ProgSnob 修正答案。
    【解决方案2】:

    只是另一个漂亮的变种

    import time
    
    bar = [
        " [=     ]",
        " [ =    ]",
        " [  =   ]",
        " [   =  ]",
        " [    = ]",
        " [     =]",
        " [    = ]",
        " [   =  ]",
        " [  =   ]",
        " [ =    ]",
    ]
    i = 0
    
    while True:
        print(bar[i % len(bar)], end="\r")
        time.sleep(.2)
        i += 1
    

    【讨论】:

      【解决方案3】:

      如果您要安装某些东西,加载栏很有用。

      animation = [
      "[        ]",
      "[=       ]",
      "[===     ]",
      "[====    ]",
      "[=====   ]",
      "[======  ]",
      "[======= ]",
      "[========]",
      "[ =======]",
      "[  ======]",
      "[   =====]",
      "[    ====]",
      "[     ===]",
      "[      ==]",
      "[       =]",
      "[        ]",
      "[        ]"
      ]
      
      notcomplete = True
      
      i = 0
      
      while notcomplete:
          print(animation[i % len(animation)], end='\r')
          time.sleep(.1)
          i += 1
      

      如果你想让它持续几秒钟,请这样做

      if i == 17*10:
          break
      

      之后

      i += 1
      

      【讨论】:

        【解决方案4】:

        Python 的内置 curses 包包含用于控制打印到终端屏幕的实用程序。

        【讨论】:

        • curses 与这篇文章无关。他只是在问一个动画循环,你可以用诅咒制作,但这不是这篇文章的答案。
        猜你喜欢
        • 2014-12-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-07-21
        • 2018-04-26
        • 1970-01-01
        相关资源
        最近更新 更多