pythonoptparse

Optparse Option Actions


I'm working with optparse, and I'm writing a script with 3 commandline arguments. The first one (-qtype) specifies whether information needs to be called from a local file, or from the web. Then depending on this, the 2nd argument (-qname) is either a string of nucleotides, or a FASTA filename. The 3rd argument (-output) is the output filename.

My question is if there is an optparse option action that I can use for the 1st argument (since the standard "store," "append," etc do not apply in this case).

Here is what I have so far: (it is likely laced with errors)

import optparse

if False:#__name__== '__main__':
    # parser object for managing input options
    parser = optparse.OptionParser()

    parser.add_option( '-qtype' ,  action = ‘?’ )
    parser.add_option( '-qname' , action = ‘?’ , […] )
    parser.add_option( '-output' , action = ‘store’ , type = ‘?’ , dest = ‘filename’ )

    # load the inputs
    args = [‘-qtype’ , ‘-qname’ , ‘-output’]
    (options , args) = parser.parse_args()

I have question marks and [...] where I am boggled over how to approach this problem.


Solution

  • Option 1: Use arguments instead of options

    This might be a viable approach since it seems you might require all three inputs from the user to run normally.

    According to the optparse docs

    A program should be able to run just fine with no options whatsoever

    In this case your solution would like

    import optparse
    import sys
    
    if __name__ == '__main__':
        parser = optparse.OptionParser()
    
        (options, args) = parser.parse_args()
    
        if len(args) != 3:
            print 'please specify all required arguments - qtype qname output_file'
            sys.exit(-1)
    
        qtype, qname, output = args
    
        if qtype == 'web':
            pass
        elif qtype == 'local':
            pass
        else:
            print 'no qtype specified! exiting'
            sys.exit(-1)
    

    Then you can use all the arguments as strings and either process them directly or turn them into files / url for web requests.

    Example command line:

    program.py  web  blah blah
    

    Option 2: Use options anyway

    import optparse
    import sys
    
    if __name__ == '__main__':
        parser = optparse.OptionParser()
    
        parser.add_option('--qtype', action='store', dest='qtype', type='string')
        parser.add_option('--qname', action='store', dest='qname', type='string')
        parser.add_option('--output', action='store', type='string', dest='filename')
    
        (options, args) = parser.parse_args()
        if options.qtype == 'web':
            pass
        elif options.qtype == 'local':
            pass
        else:
            print 'no qtype specified! exiting'
            sys.exit(-1)
    

    Example usage:

    program.py --qtype web --qname blah --output blah