Python: OptParser Module

I was trying to find a suitable method to pass arguments to my scripts. First I tried the sys.argv approach, but that left me with all the parsing and variable attribution hassle.. Then, I had a look to the getopts module, which I’d been advised to use. While browsing its page, I got over a line which said “for a more OO approach, try the OptParser module”. I’m generally not a guy of OO, ’cause all I know of it is self-taught and honestly, not that well based nor cemented. But I decided to give it a try.

Essentially, it all start with defining a function in which our allowed arguments will be defined.

def process_args():
    """To process arguments in the command line when calling the script"""

    from optparse import OptionParser

    parser = OptionParser()
    parser.add_option("-s", "--sequence", action="store", dest="sequence", help="Aminoacid Sequence")
    parser.add_option("-B", "--blastresults", action="store", dest="blast_results", default=50, help="(BLAST) Number of results to keep")
    parser.add_option("-k", "--keepdata", action="store_true", dest="keep", default=False, help="Saves PDB files and NEEDLE output to local folder")

    return parser.parse_args()

This is a small piece of the code of the previous post. The first line is to import our module, the second to define our class. Then, add your arguments. The first argument is the short flag (“-s”), the second is the long flag (“–sequence”), the third is what to do with it (store keeps the arg value, store_true/store_false keep true/false values, etc), the forth is where to save the arg (the name of the variable we can use later to access it), and etc. It’s pretty much self-explanatory, pretty much straight-forward, and hell… isn’t it useful? :)

More information:


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s