使用sys.exit()停止django命令 [英] stop django command using sys.exit()

查看:435
本文介绍了使用sys.exit()停止django命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个django命令的问题,我需要停止命令,如果一些情况发生,通常在python脚本我这样做使用sys.exit(),因为我不希望脚本仍然在做事情我尝试这个Django,不工作的另一种方式来停止命令运行?



健康和好东西。

解决方案

文档

 从django.core.management.base导入BaseCommand,CommandError 
从投票。模型导入轮询

类命令(BaseCommand):
help ='关闭指定的投票进行投票'

def add_arguments(self,parser):
parser.add_argument('poll_id',nargs ='+',type = int)

def handle(self,* args,** options):
for options [ poll_id']:
try:
poll = Poll.objects.get(pk = poll_id)
除了Poll.DoesNotExist:
raise CommandError('Poll'%s不存在'%poll_id)

poll .opened = False
poll.save()

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

ie你应该提出一个 CommandError



虽然 sys.exit 一般应该也可以正常工作(我的意思是说你不适合你 - 如果是我,我会很好奇,为什么不去)


Hi I have a problem with the django commands the thing is I need to stop the command if some condition happen, normally in python script I do this using sys.exit() because I don't want the script still doing things I try this with Django and doesn't work there is another way to stop the command running ?

Health and good things.

解决方案

from the docs:

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

class Command(BaseCommand):
    help = 'Closes the specified poll for voting'

    def add_arguments(self, parser):
        parser.add_argument('poll_id', nargs='+', type=int)

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

            poll.opened = False
            poll.save()

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

i.e. you should raise a CommandError

though sys.exit generally ought to work fine too (I mean, you said it didn't for you - if it was me I'd be curious to work out why not anyway)

这篇关于使用sys.exit()停止django命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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