1import argparse
2
3parser = argparse.ArgumentParser()
4parser.add_argument("-n", "--name", help="Name of thing")
5parser.add_argument("-s", "--size", help="Size of thing", type=int)
6args = parser.parse_args()
7
8print(args.name, args.size)
1import argparse
2
3# construct the argument parse and parse the arguments
4ap = argparse.ArgumentParser()
5ap.add_argument("-n", "--name", required=True, help="name of the user")
6args = vars(ap.parse_args())
7
8# display a friendly message to the user
9print("Hi there {}, it's nice to meet you!".format(args["name"]))
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
3if __name__ == "__main__":
4 #add a description
5 parser = argparse.ArgumentParser(description="what the program does")
6
7 #add the arguments
8 parser.add_argument("arg1", help="advice on arg")
9 parser.add_argument("arg2", help="advice on arg")
10# .
11# .
12# .
13 parser.add_argument("argn", help="advice on arg")
14
15 #this allows you to access the arguments via the object args
16 args = parser.parse_args()
17
18 #how to use the arguments
19 args.arg1, args.arg2 ... args.argn
1import argparse
2
3parser = argparse.ArgumentParser()
4parser.add_argument('file', type=argparse.FileType('r'))
5args = parser.parse_args()
6
7print(args.file.readlines())
1parser.add_argument("-v", "--verbose", action="store_true",
2 default="your default value", help="verbose output")