Python › Command-Line Interfaces (argparse)

How do you accept a variable number of arguments for a single flag, like a list of filenames?

Intermediate

Answer

Set 'nargs' to control how many values an argument consumes: '+' requires ONE OR MORE, '*' allows ZERO OR MORE, and a specific integer requires EXACTLY that many — the parsed result becomes a list instead of a single value.
parser.add_argument("--files", nargs="+", help="One or more input files")
args = parser.parse_args(["--files", "a.txt", "b.txt", "c.txt"])
print(args.files)  # ['a.txt', 'b.txt', 'c.txt']
Real-world example Accepting a list of input files to process in a batch CLI tool, like 'mytool --files a.txt b.txt c.txt'.

Common follow-ups: What's the difference in behavior between nargs='+' and nargs='*' when NO values are provided?