We help IT Professionals succeed at work.

Python 2.7 - Argparse Usage

bsumariwalla asked
Last Modified: 2017-10-20

I'm using Python 2.7 and the Argparse module to parse command line parameters.    I have the following stripped down code, but I'd like to use subparsers and parents to make the help more obvious.   I have the following usage cases that I am trying to accommodate, but I can't figure out how to do this properly with subparsers.  If someone could nudge me in the right direction with a couple of generic examples, I would appreciate it.  

script.py # script should execute and assume the -i switch
script.py -i # script should execute in interactive mode
script.py -f [fname] # The script should execute in file mode.  The script takes fname as a parameter and executes.  In my code below, I have the fname validated via another function, but I can't figure that out with subparsers
script.py -E [endpoint] -s [start_time] -e [end_time] # The script executes in endpoint mode.   The -s is mandatory with -E  and -e is optional.   However, if parameters are passed they must be validated with the valid_date function.  I have this working in the code below, but I can't figure it out with subparsers.   I may at some point also try to validate the endpoint parameter.

"-a" and "-x" are optional parameters and may be used with any of the three modes listed above.   I know this is accomplished via parents.  However, I can't get this working the closest I've come is code that doesn't error out.  However, --help does not display existence of the switches either.

import argparse
from time import time as timer
import sys
def valid_date(iso8601):
def valid_file(parser, fname):
    return fname
def file_mode(fname, audit, staging):
    print("Start in file mode.  Audit is {} and staging is {}.".format(audit, staging))
def endpoint_mode(endpoint, start_time, end_time, audit, staging):
    print("Start in endpoint mode.  Audit is {} and staging is {}.".format(audit, staging))
def interactive_mode(audit, staging):
    print("Start in interactive mode.  Audit is {} and staging is {}.".format(audit, staging))
def main():
    parser = argparse.ArgumentParser(description="This is my test ArgParse script.")
    group = parser.add_mutually_exclusive_group()
    group.add_argument("-i", \
                        dest="interactive", \
                        action="store_true", \
                        help="Run the script interactively.  This is the default " + \
                             "mode if no options are specfied.")
    group.add_argument("-f", \
                        dest="fname", \
                        help="Run the script against an input file.", \
                        metavar="FILE", \
                        type=lambda x: valid_file(parser, x))
    group.add_argument("-E", \
                        help="Run the script against a specific endpoint.",
    parser.add_argument("-a", \
                        dest="audit", \
                        action="store_true", \
                        help="Audit only.")
    parser.add_argument("-x", \
                        dest="staging", \
                        action="store_true", \
                        help="Switches queries to use staging.")
    parser.add_argument("-s", \
                        dest="start_time", \
                        help="Specify a start date.  This is mandatory with the -E switch.", \
    parser.add_argument("-e", \
                        dest="end_time", \
                        help="Specify an end date.  This optional with the -E switch.", \
    args = parser.parse_args()
    audit = args.audit
    staging = args.staging
    interactive = args.interactive
    fname = args.fname
    endpoint = args.endpoint
    start_time = args.start_time
    end_time = args.end_time
    if not len(sys.argv) > 1:
        interactive_mode(audit, staging)
    if args.interactive is True:
        interactive_mode(audit, staging)
    if '-f' in sys.argv:
        file_mode(fname, audit, staging)
    if '-E' in sys.argv:
        endpoint_mode(endpoint, start_time, end_time, audit, staging)

Open in new window

Watch Question

This problem has been solved!
(Unlock this solution with a 7-day Free Trial)
Question inactive