简体   繁体   English

如何遍历Django管理命令* args?

[英]How can I loop through Django management command *args?

I have the following code: 我有以下代码:

class Command(BaseCommand):
    help = 'Build static site output.'

    def add_arguments(self, parser):
        parser.add_argument('args')

    def handle(self, *args, **options):
        """Request pages and build output."""
        if args:
            pages = args
            available = list(get_pages())
            invalid = []
            for page in pages:
                if page not in available:
                    invalid.append(page)
            if invalid:
                msg = 'Invalid pages: {}'.format(', '.join(invalid))
                raise CommandError(msg)
        else:
            ...

However when I run this command: 但是,当我运行此命令时:

python prototypes.py build index

the command loops through each letter of the word index . 该命令循环遍历单词index每个字母。

CommandError: Invalid pages: i, n, d, e, x

I want it to detect index as one argument and if I provide more arguments with spaces in between it should be looping through those. 我希望它将index检测为一个参数,如果我提供更多的参数,并且它们之间有空格,则应该循环遍历这些参数。

If I don't add the add_arguments method it shows unrecognized argument in the console. 如果我不添加add_arguments方法,它将在控制台中显示unrecognized argument

This method fixed my problem. 这种方法解决了我的问题。

def add_arguments(self, parser):
    parser.add_argument('args', nargs='+')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM