Example 1: argparse
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("-n", "--name", help="Name of thing")
parser.add_argument("-s", "--size", help="Size of thing", type=int)
args = parser.parse_args()
print(args.name, args.size)
Example 2: python argparse
import argparse
ap = argparse.ArgumentParser()
ap.add_argument("-n", "--name", required=True, help="name of the user")
args = vars(ap.parse_args())
print("Hi there {}, it's nice to meet you!".format(args["name"]))
Example 3: how to use argparse
import argparse
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="what the program does")
parser.add_argument("arg1", help="advice on arg")
parser.add_argument("arg2", help="advice on arg")
parser.add_argument("argn", help="advice on arg")
args = parser.parse_args()
args.arg1, args.arg2 ... args.argn
Example 4: argeparse can it take a type list
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--default')
parser.add_argument('--list-type', type=list)
parser.add_argument('--list-type-nargs', type=list, nargs='+')
parser.add_argument('--nargs', nargs='+')
parser.add_argument('--nargs-int-type', nargs='+', type=int)
parser.add_argument('--append-action', action='append')
for _, value in parser.parse_args()._get_kwargs():
if value is not None:
print(value)
Example 5: python argparse file argument
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('file', type=argparse.FileType('r'))
args = parser.parse_args()
print(args.file.readlines())
Example 6: python argument parser default value
parser.add_argument("-v", "--verbose", action="store_true",
default="your default value", help="verbose output")