本文介绍了如何使Django定制管理命令参数不是必需的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在Django中编写如下的自定义管理命令-

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

现在,当我运行 python manage.py mycommand 12 时,它将在控制台上打印12。

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

现在,如果我尝试运行 python manage.py mycommand ,那么我想要该命令默认情况下在控制台上显示21。但这给了我类似的东西-

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?

推荐答案

建议:

因此,以下方法可以解决问题(如果提供,将返回值,否则返回默认值):

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)

用法:

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

这篇关于如何使Django定制管理命令参数不是必需的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-30 05:59