Django and argparse management team

I am trying to create a Django control command using argparse, however, whenever I run it, it always returns the option that is valid, since this message comes from the manage.py file:

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 correct way to use the argument parser with control commands?

Python version 2.x.

+6
source share
3 answers

The Django parameters analyze OptParser before they are passed to your Command . You should add your parameters to BaseCommand.option_list as follows:

 class Command(BaseCommand): help = 'My cool command' option_list = BaseCommand.option_list + ( make_option('--max', action='store', dest='max', type='float', default=0.0, help='Max value'),) def handle(self, *args, **options): print options['max'] 
+5
source

Instead, just change the option_list as suggested in the 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'] 
+4
source

According to the documentation , custom options can be added in the add_arguments () method.

 class Command(BaseCommand): def add_arguments(self, parser): # Positional arguments parser.add_argument('poll_id', nargs='+', type=int) # Named (optional) arguments parser.add_argument( '--delete', action='store_true', dest='delete', help='Delete poll instead of closing it', ) def handle(self, *args, **options): # ... if options['delete']: poll.delete() # ... 
0
source

Source: https://habr.com/ru/post/982245/


All Articles