argparse options code example
Example 1: how to use argparse
import argparse
if __name__ == "__main__":
#add a description
parser = argparse.ArgumentParser(description="what the program does")
#add the arguments
parser.add_argument("arg1", help="advice on arg")
parser.add_argument("arg2", help="advice on arg")
# .
# .
# .
parser.add_argument("argn", help="advice on arg")
#this allows you to access the arguments via the object args
args = parser.parse_args()
#how to use the arguments
args.arg1, args.arg2 ... args.argn
Example 2: 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 3: argparse list of options
parser.add_argument('--list',
default='all',
const='all',
nargs='?',
choices=['servers', 'storage', 'all'],
help='list servers, storage, or both (default: %(default)s)')
Example 4: python argument parser default value
parser.add_argument("-v", "--verbose", action="store_true",
default="your default value", help="verbose output")
Example 5: argparse accept only few options
...
parser.add_argument('--val',
choices=['a', 'b', 'c'],
help='Special testing value')
args = parser.parse_args(sys.argv[1:])
Example 6: python argparser flags
parser.add_argument("-v", "--verbose", action="store_true",
help="verbose output")