Python Django 管理命令参数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27611468/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Django Management Command Argument
提问by Peter Graham
I need to pass in an integer argument to a base command in Django. For instance if my code was
我需要将整数参数传递给 Django 中的基本命令。例如,如果我的代码是
from django.core.management import BaseCommand
class Command(BaseCommand):
def handle(self, *args, **options, number_argument):
square = number_argument ** 2
print square
I would want to say python manage.py square_command 4 and have it return 16. Is there a way I can pass an argument through the terminal to the command I want to run?
我想说 python manage.py square_command 4 并让它返回 16。有没有办法可以通过终端将参数传递给我想运行的命令?
采纳答案by acidjunk
Add this method to your Command class:
将此方法添加到您的 Command 类:
def add_arguments(self, parser):
parser.add_argument('my_int_argument', type=int)
You can then use your option in the code, like this:
然后您可以在代码中使用您的选项,如下所示:
def handle(self, *args, **options):
my_int_argument = options['my_int_argument']
The benefit of doing it this way is that the help
output is automatically generated for manage.py my_command --help
这样做的好处是help
输出是自动生成的manage.py my_command --help