16

Minimum verifiable example:

import argparse

parser = argparse.ArgumentParser(description='...')
parser.add_argument('-f','--file', type=str, nargs='+', help='file list')

args = parser.parse_args()

print(args.sparse[:])

And the idea is that I call this as:

python my_script.py -f f1 f2 f3 -f some_other_file1 some_other_file2 ...

And the output would be:

[ [ f1 f2 f3 ] [ some_other_file1 some_other_file2 ] ]

However, in this case, all that is printed out is:

 [ some_other_file1 some_other_file2 ]
Chris
  • 28,822
  • 27
  • 83
  • 158
  • Possible duplicate of [Using the same option multiple times in Python's argparse](https://stackoverflow.com/questions/36166225/using-the-same-option-multiple-times-in-pythons-argparse) – Aurora Wang Dec 10 '18 at 20:16

1 Answers1

22

action='append' may be what you want:

import argparse

parser = argparse.ArgumentParser(description='...')
parser.add_argument('-f','--file', type=str, nargs='+', action='append', 
help='file list')

args = parser.parse_args()

print(args.file)

will give

$ python my_script.py -f 1 2 3 -f 4 5
[['1', '2', '3'], ['4', '5']]
Michael H.
  • 3,323
  • 2
  • 23
  • 31