How to make a Django custom management command arg

2020-07-02 10:44发布

问题:

I am trying to write a custom management command in django like below-

class Command(BaseCommand):

    def add_arguments(self, parser):
        parser.add_argument('delay', type=int)

    def handle(self, *args, **options):
        delay = options.get('delay', None)
        print delay

Now when I am running python manage.py mycommand 12 it is printing 12 on console. Which is fine.

Now if I try to run python manage.py mycommand then I want that, the command prints 21 on console by default. But it is giving me something like this-

usage: manage.py mycommand [-h] [--version]
                           [-v {0,1,2,3}]
                           [--settings SETTINGS]
                           [--pythonpath PYTHONPATH]
                           [--traceback]
                           [--no-color]
                           delay

So now, how should I make the command argument "not required" and take a default value if value is not given?

回答1:

One of the recipes from the documentation suggests:

For positional arguments with nargs equal to ? or *, the default value is used when no command-line argument was present.

So following should do the trick (it will return value if provided or default value otherwise):

parser.add_argument('delay', type=int, nargs='?', default=21)

Usage:

$ ./manage.py mycommand
21
$ ./manage.py mycommand 4
4


回答2:

You can use the dash syntax for optional keyword arguments:

class Command(BaseCommand):

    def add_arguments(self, parser):
        parser.add_argument("-d", "--delay", type=int)

    def handle(self, *args, **options):
        delay = options["delay"] if options["delay"] else 21
        print(delay)

Use:

$ python manage.py mycommand -d 4
4
$ python manage.py mycommand --delay 4
4
$ python manage.py mycommand
21

Docs:

https://docs.djangoproject.com/en/2.2/howto/custom-management-commands/#s-accepting-optional-arguments

Simple explanation:

https://simpleisbetterthancomplex.com/tutorial/2018/08/27/how-to-create-custom-django-management-commands.html#handling-arguments