Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django management command and argparse

Tags:

python

django

I'm trying to create a Django management command with argparse, however whenever I run it, it always returns no such option which is valid, as this message comes from the manage.py:

class Command(BaseCommand):
    def handle(self, *args, **options):
        parser = argparse.ArgumentParser('Parsing arguments')
        parser.add_argument('--max', type=float, store)
        args = parser.parse_args(sys.argv[2:])

What would be the right way to use some argument parser with management commands?

Python version 2.x .

like image 963
user2194805 Avatar asked Feb 10 '15 07:02

user2194805


People also ask

What is Django management command?

Basically, a Django management command is built from a class named Command which inherits from BaseCommand. 1) help: It tells what actually the command does. Run the following command and see the help. python manage.py stats --help.

What is the use of Argparse in Python?

The argparse module makes it easy to write user-friendly command-line interfaces. The program defines what arguments it requires, and argparse will figure out how to parse those out of sys.argv .

What is manage py in Python?

It is your tool for executing many Django-specific tasks -- starting a new app within a project, running the development server, running your tests... It is also an extension point where you can access custom commands you write yourself that are specific to your apps.

What is dest in Argparse?

The argparse module provides a convenient interface to handle command-line arguments. It displays the generic usage of the program, help, and errors. The parse_args() function of the ArgumentParser class parses arguments and adds value as an attribute dest of the object. dest identifies an argument.


2 Answers

In Django options are parsed with rules given in add_arguments method of BaseCommand. You should add your options to parser.add_argument, which use argparse lib like this:

class Command(BaseCommand):
    help = 'My cool command'

    def add_arguments(self, parser):
        # Named (optional) arguments
        parser.add_argument(
              '--max',
               action='store',
               dest='max',
               type='float',
               default=0.0,
               help='Max value'
        )

    def handle(self, *args, **options):
        print options['max']
like image 100
Yossi Avatar answered Oct 13 '22 01:10

Yossi


Instead, just modify the option_list, as suggested in docs:

from optparse import make_option

class Command(BaseCommand):
    option_list = BaseCommand.option_list + (
        make_option('--max',
            action='store',
            type='float',
            dest='max'), 
        )

    def handle(self, *args, **options):
        print options['max']
like image 45
alecxe Avatar answered Oct 13 '22 00:10

alecxe