11

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 .

Alasdair
310k59 gold badges605 silver badges534 bronze badges
asked Feb 10, 2015 at 7:11
1

3 Answers 3

14

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']
freezed
1,3491 gold badge18 silver badges40 bronze badges
answered Feb 10, 2015 at 7:30
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, it' s fine, however a comma is missing. For later usage, can You please add it?
5

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']
answered Feb 10, 2015 at 7:30

1 Comment

I think a comma and a parenthesis is missing from your code... . Anyway thanks!
2

According to the docs, 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()
 # ...
answered Jan 9, 2019 at 7:26

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.