Skip to content

Instantly share code, notes, and snippets.

@DavidAntliff
Created November 30, 2016 00:33
Show Gist options
  • Save DavidAntliff/c99c24d9f87730d213c2c403b9cbde4c to your computer and use it in GitHub Desktop.
Save DavidAntliff/c99c24d9f87730d213c2c403b9cbde4c to your computer and use it in GitHub Desktop.
Python: accept multiple instances of a command line argument
"""
Copyright 2016 David Antliff; this file is licensed under the terms of the Apache license version 2.0. For a full copy of the license, see https://www.apache.org/licenses/LICENSE-2.0
Accept two styles of repeated options on the command line.
Style 1 - each instance repeats the option itself. E.g.
$ python prog --option A --option B
Style 2 - each instance occurs after a single instance of the option. E.g.
$ python prog --option C D E
This solution combines both styles. E.g.
$ python ./test_argparse.py --option A --option B --option C D E
['A', 'B', 'C', 'D', 'E']
"""
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--option", nargs="+", action="append", dest="options")
args = parser.parse_args()
# args.options will be a list of lists, so flatten with:
options = [item for sublist in args.options for item in sublist]
print options
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment