在函数下没有换行符的打印在 Python 中不起作用 [英] Print without newline under function doesn't work as it should in Python
问题描述
我正在为我的上传脚本制作一个进度条,因此我想打印一行多个#",但我无法让它工作.当我告诉 Python 不要添加换行符时,它确实删除了它,但它在函数下无法按预期工作.在 Python 3 中使用 "print ('#', end='')" 或在 Python 2 中使用 "print '#'," 将其删除,但在函数下执行时,在整个函数完成之前它不会打印任何内容,它不应该像正常打印一样等待.
I'm doing a progressbar for my uploading script and therefor i want to print a row of multiple '#' but i can't get it to work. When i tell Python to not add newline it does remove it but it doesn't work as expected under functions. Using "print ('#', end='')" in Python 3 or "print '#'," in Python 2 removes it but when executed under a functions it doesn't print anything out until the whole function is finished, it should not wait just like normal print.
import time
i = 0
def status():
print('#', end='')
while i < 60:
status()
time.sleep(1)
i += 1
这应该每秒打印 '#' 但它没有.它会在 60 秒后将它们全部打印出来.仅使用 print('#') 按预期每秒打印一次.我真的需要解决这个问题.请帮忙!
This should print '#' every second but it doesn't. It prints them all after 60 seconds. Using just print('#') prints it out every second as expected. I really need a fix for this. Please help!
解决办法:每次打印后sys.stdout.flush()":)
Solution: "sys.stdout.flush()" after each print :)
推荐答案
您可能需要在每次 print
调用后刷新输出缓冲区.请参阅如何刷新 Python 打印的输出?
You probably need to flush the output buffer after each print
invocation. See How to flush output of Python print?
这篇关于在函数下没有换行符的打印在 Python 中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!