Search code examples
pythonargparseoptparse

groking command line parameters in a python script


I am relatively new to python. I want to write a script and pass it parameters like this:

myscript.py --arg1=hello --arg2=world

In the script, I want to access the arguments arg1 and arg2. Can anyone explains how to access command line parameters in this way?


Solution

  • Argparse is part of the standard library (as of versions 2.7 and 3.2). This is the module I use to handle all my command line parsing although there is also optparse (which is now deprecated) and getopt.

    The following is a simple example of how to use argparse:

    import sys, argparse
    
    def main(argv=None):
    
        if argv is None:
            argv=sys.argv[1:]
    
        p = argparse.ArgumentParser(description="Example of using argparse")
    
        p.add_argument('--arg1', action='store', default='hello', help="first word")
        p.add_argument('--arg2', action='store', default='world', help="second word")
    
        # Parse command line arguments
        args = p.parse_args(argv)
    
        print args.arg1, args.arg2
    
        return 0
    
    if __name__=="__main__":
        sys.exit(main(sys.argv[1:]))
    

    Edit: Note that the use of the leading '--' in the calls to add_arguments make arg1 and arg2 optional arguments, so I have supplied default values. If you want to program to require two arguments, remove these two leading hypens and they will become required arguments and you won't need the default=... option. (Strictly speaking, you also don't need the action='store' option, since store is the default action).