python - Django管理命令动态一行输出

标签 python django printing

我有一个 Django 管理命令,它执行相当多的处理,所以我让它以百分比的形式输出它的进度。我想使用答案中描述的技术 herehere .我知道 from the Django docs在管理命令中使用时,sys.stdout 需要替换为 self.stdout,但我仍然没有运气。它是 python 2.7,所以我不能将 end kwarg 提供给 print。这是我在 Command 对象的 handle 中尝试过的事情之一:

i = 0
for thing in query:
    self.stdout.write("\r%%%s" % (100 * float(i) / float(query.count()))
    i += 1

我已经尝试了类似问题的答案中描述的其他几种技术,包括使用 ANSI escape sequences . Django管理命令打印输出的方式有什么特别之处吗?我怎样才能达到我想要的效果?

最佳答案

tl;dr

stdout 输出默认是缓冲的,所以手动刷新:

import time

from django.core.management.base import BaseCommand

class Command(BaseCommand):
    help = "My shiny new management command."

    def handle(self, *args, **options):
        self.stdout.write("Writing progress test!")
        for i in range(100):
            self.stdout.write("%{}".format(i), ending='\r')
            self.stdout.flush()
            time.sleep(0.01)

引用

我关注了this issue几年前有人开了,this SO thread ;查看更多详细信息和其他解决方案,例如 python -u option .

关于python - Django管理命令动态一行输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30957273/

相关文章:

python - Django 。从 HDD 检索并打开 zip 文件

python - Django 高级搜索

Python - 水平打印两个字符串,带有 |

java - 默认 switch case 之后的 if 语句 - Java

python - 矩形没有出现在 opencv 中

python - Ansible 创建一个 virtualenv

python - 'print' 和 'return' 有什么区别?

python - 按名称调用 Python 方法

python - Django 中的 django.views.generic.list.ListView 和 django.views.generic.ListView 有什么区别?

printing - 使用 netcat 打印 postscript