How to run a python script with options
Question: I'm looking for an efficient way to write a python script that can be called
using the hyphen-single-letter-space-parameter convention (e.g. `python
script.py -f /filename -t type -n 27`, where `f`, `t`, and `n` are the single
letters corresponding to option types and `/filename`, `type`, and `27` are
their values). I am aware of the `sys` library and its `sys.argv` function as
a means of grabbing the space-delimited strings following the call (see [call
program with arguments](http://stackoverflow.com/questions/3316961/call-
program-with-arguments/3317004#3317004)), but is there a sophisticated way to
process these strings when they follow the convention mentioned above?


Answer: You want the [`argparse`
module](http://docs.python.org/2/library/argparse.html#module-argparse) in the
python standard library.

The argparse module contains an `ArgumentParser` class which you can use to
parse the arguments provided by `sys.argv`

Usage example:

    
    
    import argparse
    import sys
    
    parser = argparse.ArgumentParser(description="Does some awesome things.")
    parser.add_argument('message', type=str, help="pass a message into the script")
    
    if __name__ == '__main__':
        args = parser.parse_args(sys.argv[1:])
        print args.message
    

For more details, such as how to incorporate optional, default, and multiple
arguments, [see the
documentation](http://docs.python.org/2/library/argparse.html#module-
argparse).

