假设command的文件是test1.py
django command的option选项需要是用make_option模块来创建,下面是简单的示例代码:
from django.core.management.base import BaseCommand, CommandError
from optparse import make_option
class Command(BaseCommand):
option_list = BaseCommand.option_list + (
make_option('--test2', #用户输入
action='store_true',
dest='test2',
default=False, #是否是默认的option
help="option's help message"), #此option的帮助信息,将在--help下显示
)
def handle(self, *args, **options):
if options['test2']: #判断此选项是否被选择
print "test2 option" #执行选项任务
此时,如果你在运行的时候输入--help选项,应该会有下面这样的信息提示:
python manage.py test1 --help
Usage: manage.py test1 [options]
Options:
-v VERBOSITY, --verbosity=VERBOSITY
Verbosity level; 0=minimal output, 1=normal output,
2=verbose output, 3=very verbose output
--settings=SETTINGS The Python path to a settings module, e.g.
"myproject.settings.main". If this isn't provided, the
DJANGO_SETTINGS_MODULE environment variable will be
used.
--pythonpath=PYTHONPATH
A directory to add to the Python path, e.g.
"/home/djangoprojects/myproject".
--traceback Print traceback on exception
--test2 option's help message
--version show program's version number and exit
-h, --help show this help message and exit
python manage.py test1 --test2
将看到:test2 option