Django可以使用manage.py自定义命令返回值吗?怎么样,为什么不呢? [英] Can Django manage.py custom commands return a value? How, or why not?

查看:163
本文介绍了Django可以使用manage.py自定义命令返回值吗?怎么样,为什么不呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

遵循以下文档:
https://docs.djangoproject.com/ en / dev / howto / custom-management-commands /

我创建了自己的自定义命令>

I created my own custom command (called something else but example shown below):

from django.core.management.base import BaseCommand, CommandError
from polls.models import Poll

class Command(BaseCommand):
    args = '<poll_id poll_id ...>'
    help = 'Closes the specified poll for voting'

    def handle(self, *args, **options):
        for poll_id in args:
            try:
                poll = Poll.objects.get(pk=int(poll_id))
            except Poll.DoesNotExist:
                raise CommandError('Poll "%s" does not exist' % poll_id)

            poll.opened = False
            poll.save()

            self.stdout.write('Successfully closed poll "%s"' % poll_id)

        return "Yay"

问题是如何返回像Yay这样的字符串不起作用?
我做错了或是不可能吗?

The question is how come returning a string like "Yay" does not work? Am I doing it wrong or is it not possible?

当我从我的角度调用自定义命令时,我做了一些类似于:

When I call the custom command from my view, I do something like:

     value = call_command('call_custom_command', parameter)
     print value

,但该值显示为无。

推荐答案

如果想获得 call_command()的输出,你需要捕获stdout。以下是您可以如何做:

If you want to get the output of call_command(), you need to capture stdout. Here's how you can do it:

out = StringIO()
call_command('call_custom_command', stdout=out)

value = out.getvalue()
print value

该技术实际上用于 django测试,用于测试管理命令。

This technique is actually used in django tests for testing management commands.

演示:

>>> from django.core.management import call_command
>>> from StringIO import StringIO
>>> out = StringIO()
>>> call_command('validate', stdout=out)
>>> out.getvalue()
'0 errors found\n'

希望有所帮助。

这篇关于Django可以使用manage.py自定义命令返回值吗?怎么样,为什么不呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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