python cli with argparse code example
Example 1: 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 2: argparse python
def create_parser(arguments):
"""Returns an instance of argparse.ArgumentParser"""
parser = argparse.ArgumentParser(
description="Description of your code")
parser.add_argument("argument", help="mandatory or positional argument")
parser.add_argument("-o", "--optional",
help="Will take an optional argument after the flag")
namespace = parser.parse_args(arguments)
return namespace
Example 3: python argparser flags
parser.add_argument("-v", "--verbose", action="store_true",
help="verbose output")