braindump
braindump

Reputation: 309

argparse: Get undefined number of arguments

I'm building a script which uses arguments to configure the behavior and shall read an undefined number of files. Using the following code allows me to read one single file. Is there any way to accomplish that without having to set another argument, telling how many files the script should read?

parser = argparse.ArgumentParser()
parser.add_argument("FILE", help="File to store as Gist")
parser.add_argument("-p", "--private", action="store_true", help="Make Gist private")

Upvotes: 10

Views: 11428

Answers (2)

Calvin Cheng
Calvin Cheng

Reputation: 36506

import argparse

parser = argparse.ArgumentParser()

parser.add_argument('-FILE', action='append', dest='collection',
                    default=[],
                    help='Add repeated values to a list',
                    )

Usage:

python argparse_demo.py -FILE "file1.txt" -FILE "file2.txt" -FILE "file3.txt"

And in your python code, you can access these in the collection variable, which will essentially be a list, an empty list by default; and a list containing the arbitrary number of arguments you supply to it.

Upvotes: 6

Collin
Collin

Reputation: 12287

Yes, change your "FILE" line to:

parser.add_argument("FILE", help="File to store as Gist", nargs="+")

This will gather all the positional arguments in a list instead. It will also generate an error if there's not at least one to operate on.

Check out the nargs documentation

Upvotes: 25

Related Questions