在Django管理命令中显示命令帮助

时间:2019-09-27 02:47:09

标签: python django

如果没有足够有意义的参数来执行命令,我想显示manage.py <command> help的输出。

我的代码如下:

class Command(BaseCommand):
    def __init__(self, *args, **kwargs):
        super(Command, self).__init__(*args, **kwargs)

    def add_arguments(self, parser):
        parser.add_argument(
            'args', metavar='item', nargs='+',
            help="item = 'users'|'data'|..."
        )

    def handle(self, *args, **options):
        items = [x.lower() for x in set(args)]
        if not items:
            call_command('startapp', '--help')

call_command()似乎是致电帮助的一种昂贵方式。是否可以调用self进行相同操作的方法?没有call_command()的输出看起来像这样...

$ python manage.py startapp
usage: manage.py startapp [-h] [--version] [-v {0,1,2,3}]
                          [--settings SETTINGS] [--pythonpath PYTHONPATH]
                          [--traceback] [--no-color] [--force-color]
                          item [item ...]
manage.py startapp: error: the following arguments are required: item

我希望它显示manage.py startapp --help的完整输出而不显示

manage.py startapp: error: the following arguments are required: item

1 个答案:

答案 0 :(得分:0)

您可以使用self.print_help方法。例如:

    def handle(self, *args, **options):
        items = [x.lower() for x in set(args)]
        if not items:
            self.print_help('manage.py', '<your command name>')
            sys.exit(1)