Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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")
like image 696
braindump Avatar asked Nov 04 '12 15:11

braindump


2 Answers

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

like image 198
Collin Avatar answered Nov 15 '22 13:11

Collin


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.

like image 28
Calvin Cheng Avatar answered Nov 15 '22 13:11

Calvin Cheng