【问题标题】:Dynamic one-line output in Django management commandDjango管理命令中的动态一行输出
【发布时间】:2015-09-06 13:35:00
【问题描述】:

我有一个 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 管理命令打印输出的方式有什么特别之处吗?怎样才能达到我想要的效果?

【问题讨论】:

    标签: python django printing


    【解决方案1】:

    tl;博士

    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

    【讨论】:

    • 谢谢!我一直在做writeending='\r' 没有flush() 并把我的头发拉出来!
    猜你喜欢
    • 1970-01-01
    • 2021-09-21
    • 1970-01-01
    • 2015-09-18
    • 2012-05-03
    • 2017-09-02
    • 2018-11-19
    • 2015-01-14
    • 1970-01-01
    相关资源
    最近更新 更多