如何在 Python 中让一条线在屏幕上爬行?

How to make a line crawl across the screen in Python?

print('Loading Documents...')
LoadDocuments() #Function That Loads the Documents
for i in range(0, 30, 1):
    print("-", end="")
    time.sleep(0.1)
print(" ")
print('Documents Loaded')

我想要它做的是打印 Loading Documents... 然后有一条线在屏幕上爬行的动画

相反,它打印 Loading Documents,然后几秒钟后,该行中的所有破折号立即弹出

有什么想法吗?

输出通常是行缓冲的,这意味着当您 print 一行的一部分时,它可能不会显示,直到您完成 print 行的其余部分。

你可以改变缓冲,但更简单的解决方案是每次你想强制它显示你拥有的内容时显式调用 flush on the stdout 流(print 通常打印到)远:

print('Loading Documents...')
LoadDocuments() #Function That Loads the Documents
for i in range(0, 30, 1):
    print("-", end="")
    sys.stdout.flush()
    time.sleep(0.1)
print(" ")
print('Documents Loaded')

在这种情况下,直接在 stdout 上也使用 write 可能会更干净,只是为了明确表示您正在做低级 I/O 而不是正常的高级 print 机制:

print('Loading Documents...')
LoadDocuments() #Function That Loads the Documents
for i in range(0, 30, 1):
    sys.stdout.write('-')
    sys.stdout.flush()
    time.sleep(0.1)
print(" ")
print('Documents Loaded')

这在文档中有解释......但前提是你知道去哪里看,并且已经理解了其中的大部分......

print explains that sys.stdout is the default file that gets printed to, then sys.stdout 说:

These streams are regular text files like those returned by the open() function. Their parameters are chosen as follows: … When interactive, standard streams are line-buffered … You can override this value with the -u command-line option.

如果你按照 link 到 -u,它说:

Force the binary layer of the stdout and stderr streams (which is available as their buffer attribute) to be unbuffered. The text I/O layer will still be line-buffered if writing to the console…

然后你必须从 open 文本文件 中阅读一些 link 才能到达 io 并阅读几乎整个模块文档以弄清楚如何访问和重新包装 sys.stdout.buffer.raw 或仅调用 sys.stdout.flush.

您似乎想向您的用户显示某种 "progress"。

我建议你使用 progress

示例:

from progress.bar import Bar

bar = Bar('Processing', max=20)
for i in range(20):
    # Do some work
    bar.next()
bar.finish()

您必须安装此第 3 方软件包,因为它不是标准库的一部分。通常这很简单:

pip install progress