how to integrate optparse options with the variables names in python

1.9k views Asked by At

I am very newbie to python and to optparse module in general. I have figured out how to add options in python script using optparse but having trouble linking the options with my variable names in python.

import sys
from optparse import OptionParser

def main ():
    parser = OptionParser()
    parser.add_option("-f", "--file", dest="in_filename",
                      help="Input fasta file", metavar="FILE")
    parser.add_option("-o", "--out", dest="out_filename",
                      help="Output fasta file", metavar="FILE")
    parser.add_option("-i", "--id", dest="id",
                      help="Id name to change", metavar="ID")
    (options,args) = parser.parse_args()

    with open(f, 'r') as fh_in:
        with open(o, 'w') as fh_out:
            id = i
            result = {}
            count = 1
            for line in fh_in:
                line = line.strip()
                if line.startswith(">"):
                    line = line[1:]
                    result[line] = id + str(count)
                    count = count + 1
                    header = ">" + str(result[line])
                    fh_out.write(header)
                    fh_out.write("\n")
                else:
                    fh_out.write(line)
                    fh_out.write("\n")

main()

When i run this i get this below traceback and error:

python header_change.py -f consensus_seq.txt -o consensus_seq_out.fa -i "my_test"
Traceback (most recent call last):
  File "/Users/upendrakumardevisetty/Documents/git_repos/scripts/header_change.py", line 36, in <module>
    main()
  File "/Users/upendrakumardevisetty/Documents/git_repos/scripts/header_change.py", line 18, in main
    with open(f, 'r') as fh_in:
NameError: global name 'f' is not defined

Can someone point to me what i am doing wrong.

1

There are 1 answers

0
abarnert On BEST ANSWER

You've got two problems here.


First, as the optparse tutorial shows, optparse doesn't create global variables, it creates attributes in the options namespace that it returns:

parse_args() returns two values:

  • options, an object containing values for all of your options—e.g. if --file takes a single string argument, then options.file will be the filename supplied by the user, or None if the user did not supply that option
  • args, the list of positional arguments leftover after parsing options

So, if the user typed -f, you're not going to have f, you're going to have options.f.


Second, f isn't the right name anyway. You explicitly specified a different destination, instead of the default:

parser.add_option("-f", "--file", dest="in_filename",
                  help="Input fasta file", metavar="FILE")

So it's going to do what you asked and store the file in in_filename.


And likewise for the other options. So, your code should start off like this:

with open(options.in_filename, 'r') as fh_in:
    with open(options.out_filename, 'w') as fh_out: