Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

stop django command using sys.exit()

Tags:

django

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.

like image 612
Alain Abrahan Avatar asked Jan 14 '16 19:01

Alain Abrahan


People also ask

How do I exit Django?

Though the message in the console states that Ctrl+Break should be used to quit the server, it is not possible; one can only use Ctrl+F4 works to close the console.

What is sys exit in Python?

exit() function allows the developer to exit from Python. The exit function takes an optional argument, typically an integer, that gives an exit status. Zero is considered a “successful termination”.

How to use the exit command in Python?

Exit Programs With the quit() Function in Python This site module contains the quit() function,, which can be used to exit the program within an interpreter. The quit() function raises a SystemExit exception when executed; thus, this process exits our program.


1 Answers

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)

like image 65
Anentropic Avatar answered Oct 24 '22 15:10

Anentropic