1import argparse
2
3parser = argparse.ArgumentParser()
4
5# By default it will fail with multiple arguments.
6parser.add_argument('--default')
7
8# Telling the type to be a list will also fail for multiple arguments,
9# but give incorrect results for a single argument.
10parser.add_argument('--list-type', type=list)
11
12# This will allow you to provide multiple arguments, but you will get
13# a list of lists which is not desired.
14parser.add_argument('--list-type-nargs', type=list, nargs='+')
15
16# This is the correct way to handle accepting multiple arguments.
17# '+' == 1 or more.
18# '*' == 0 or more.
19# '?' == 0 or 1.
20# An int is an explicit number of arguments to accept.
21parser.add_argument('--nargs', nargs='+')
22
23# To make the input integers
24parser.add_argument('--nargs-int-type', nargs='+', type=int)
25
26# An alternate way to accept multiple inputs, but you must
27# provide the flag once per input. Of course, you can use
28# type=int here if you want.
29parser.add_argument('--append-action', action='append')
30
31# To show the results of the given option to screen.
32for _, value in parser.parse_args()._get_kwargs():
33 if value is not None:
34 print(value)
35
1import argparse
2
3parser = argparse.ArgumentParser()
4parser.add_argument('file', type=argparse.FileType('r'))
5args = parser.parse_args()
6
7print(args.file.readlines())
1...
2parser.add_argument('--val',
3 choices=['a', 'b', 'c'],
4 help='Special testing value')
5
6args = parser.parse_args(sys.argv[1:])
1parser.add_argument("-v", "--verbose", action="store_true",
2 help="verbose output")