1

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.

2
  • First, please print the whole traceback, not just the error string. In this case we can probably guess where it happened, but it's better to not make people guess. Commented Nov 8, 2014 at 2:39
  • As a side note, is there a reason you're using optparse? As the docs explain, it's deprecated in 2.7/3.2. Unless you need your program to run in 2.6 or 3.1, it's better to use argparse—especially if you're just learning; no reason to learn something that's already out of date. Commented Nov 8, 2014 at 2:44

1 Answer 1

5

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:
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.