How to make a Django custom management command argument not required?(如何使 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?
推荐答案
文档 建议:
对于 nargs 等于 ? 或 * 的位置参数,当不存在命令行参数时使用 default 值.
For positional arguments with nargs equal to
?or*, thedefaultvalue 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)
用法:
$ ./manage.py mycommand
21
$ ./manage.py mycommand 4
4
这篇关于如何使 Django 自定义管理命令参数不需要?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何使 Django 自定义管理命令参数不需要?
基础教程推荐
- 由Python将MP3转换为MIDI(类型错误:无法加载插件:mtg-Melodia:Melodia) 2022-01-01
- 在 Celery 工作人员中捕获 Heroku SIGTERM 以优雅地关 2022-01-01
- 与常规 dict 相比,Python manager.dict() 非常慢 2022-01-01
- pyserial - 可以从线程 a 写入串行端口,是否阻塞从线程 b 读取? 2022-01-01
- 用 Python 编写 Fortran 无格式文件 2022-01-01
- 使用生成器和迭代器时 Python 多循环失败 2022-01-01
- 将 x 轴刻度更改为自定义字符串 2022-01-01
- Discord.py 缺少必需的参数 2022-01-01
- numpy float:比算术运算中内置的慢 10 倍? 2022-01-01
- 尝试制作WhatsApp机器人 2022-01-01
