按照文档: https://docs.djangoproject.com/en/dev/howto/custom-management-commands/
我创建了自己的自定义命令(称为其他命令,但示例如下所示):
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”这样的字符串不起作用? 是我做错了还是不可能?
当我从 View 中调用自定义命令时,我会执行以下操作:
value = call_command('call_custom_command', parameter)
print value
但该值显示为无。
最佳答案
如果你想得到call_command()
的输出,你需要捕获stdout。你可以这样做:
out = StringIO()
call_command('call_custom_command', stdout=out)
value = out.getvalue()
print value
这个技术实际上用在 django tests用于测试管理命令。
演示:
>>> from django.core.management import call_command
>>> from StringIO import StringIO
>>> out = StringIO()
>>> call_command('validate', stdout=out)
>>> out.getvalue()
'0 errors found\n'
希望对您有所帮助。
关于python - Django manage.py 自定义命令可以返回值吗?如何,或者为什么不?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22571320/