简体   繁体   中英

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 .

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.

If I don't add the add_arguments method it shows unrecognized argument in the console.

This method fixed my problem.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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