Argparse: Get an undefined number of arguments

I am creating a script that uses arguments to configure behavior and must read an undefined number of files. Using the following code, I can read one file. Is there a way to do this without having to set another argument, indicating 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") 
+8
python argparse
source share
2 answers

Yes, change the line "FILE" to:

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

This will collect all the positional arguments in the list. This will also result in an error if at least one does not work.

View nargs documentation

+22
source share
 import argparse parser = argparse.ArgumentParser() parser.add_argument('-FILE', action='append', dest='collection', default=[], help='Add repeated values to a list', ) 

Using:

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

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

+5
source share

All Articles