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中从Azure BLOB存储中读取文件 2022-01-01
- 使用大型矩阵时禁止 Pycharm 输出中的自动换行符 2022-01-01
- 包装空间模型 2022-01-01
- PANDA VALUE_COUNTS包含GROUP BY之前的所有值 2022-01-01
- Plotly:如何设置绘图图形的样式,使其不显示缺失日期的间隙? 2022-01-01
- 无法导入 Pytorch [WinError 126] 找不到指定的模块 2022-01-01
- 在同一图形上绘制Bokeh的烛台和音量条 2022-01-01
- PermissionError: pip 从 8.1.1 升级到 8.1.2 2022-01-01
- 求两个直方图的卷积 2022-01-01
- 修改列表中的数据帧不起作用 2022-01-01
