10

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")

2 Answers 2

25

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

Sign up to request clarification or add additional context in comments.

2 Comments

That's it, thanks. I wonder why it's not in the argparse tutorial.
This is glorious
6
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.