Reputation: 18754
In Python, is there a way to specify an unlimited number of arguments to a command line option ? For example something like python myscript.py --use-files a b c d e
. Note that I strictly want to use a command line option e.g. I don't just want python myscript.py a b c d e
Upvotes: 1
Views: 223
Reputation: 363063
Command-line options are simple with stdlib argparse module. Using nargs="*"
allows arbitrarily many arguments to be supplied for an option:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--use-files', nargs='*', default=['a', 'b'])
args = parser.parse_args()
print(args)
Outputs:
$ python /tmp/spam.py
Namespace(use_files=['a', 'b'])
$ python /tmp/spam.py --use-files hello world
Namespace(use_files=['hello', 'world'])
$ python /tmp/spam.py --use-files aleph-null bottles of beer on the wall, aleph-null bottles of beer, take one down pass it around, aleph-null bottles of beer on the wall
Namespace(use_files=['aleph-null', 'bottles', 'of', 'beer', 'on', 'the', 'wall,', 'aleph-null', 'bottles', 'of', 'beer,', 'take', 'one', 'down', 'pass', 'it', 'around,', 'aleph-null', 'bottles', 'of', 'beer', 'on', 'the', 'wall'])
Upvotes: 4