Django管理命令中的动态单行输出 [英] Dynamic one-line output in Django management command

查看:39
本文介绍了Django管理命令中的动态单行输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个执行大量处理的Django管理命令,因此我将其进度输出为一个百分比.我想使用此处或<请在href ="https://stackoverflow.com/questions/3249524/print-in-one-line-dynamically">此处.我从Django文档中 在管理命令中使用> sys.stdout 时,需要将其替换为 self.stdout ,但我仍然没有运气.它是python 2.7,所以我不能将 end kwarg赋予 print .这是我在Command对象的 handle 中尝试过的事情之一:

I have a Django management command that does quite a bit of processing, so I have it outputting its progress as a percentage. I'd like to use a technique as described in the answers here or here. I'm aware from the Django docs that sys.stdout needs to be replaced with self.stdout when used inside a management command, but I'm still having no luck. It's python 2.7, so I can't give the end kwarg to print. Here's one of the things I've tried in handle of the Command object:

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

我已经尝试了类似问题的答案中描述的其他几种技术,包括使用 ANSI转义序列.Django管理命令打印输出的方式有什么特别之处吗?如何获得想要的效果?

I've tried several other techniques described in answers to similar questions, including using ANSI escape sequences. Is there something special about the way that Django management commands print output? How can I achieve the effect I'm looking for?

推荐答案

tl; dr

stdout输出默认情况下是缓冲的,因此请手动刷新:

tl;dr

stdout output is buffered by default, so flush manually:

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)

参考

我关注了这个问题,几年前有人打开了,然后 python -u选项.

Reference

I followed this issue that someone opened a few years back, and this SO thread; see both for longer details and other solutions, such as the python -u option.

这篇关于Django管理命令中的动态单行输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆