给django command写option选项

        我在 如何让django自动地定期执行中提及到django command的用法,这里顺带简单说一下关于django command的option选项应该怎么写。
        假设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

转载于:https://my.oschina.net/vincent67/blog/180811

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值