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")
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With