Hello,
A python beginner question on passing filename thru argument. My code is:
#!/usr/bin/python
import sys, getopt
import os
def main(argv):
try:
opts, args = getopt.getopt(sys.argv[1:],"hi:o:ce", ["help", "inputfile", "outputdir", "containment", "error_tolerance"])
except getopt.GetoptError:
usage()
print("Usage: %s -i inputfile -o outputdirectory -c containment -e error_tolerance" % sys.argv[0])
sys.exit(2)
for opt, arg in opts:
if opt == '-h':
print 'this_script.py -i <inputfile> -o <outputdir> -c <containment> -e <error_tolerance>'
sys.exit()
elif opt in ("-i", "--infile"):
inputfile = arg #Is this the right way to pass filename thru argument?
elif opt in ("-o", "--outdir"):
outputdir = arg
elif opt == '-c':
containment = arg
elif opt == '-e':
error_pct = arg
if __name__ == '__main__':
main(sys.argv[1])
def get_overlap_data(m4_filename):
containment_tolerance = containment
permitted_error_pct = error_pct
overlap_data = {}
contained_reads = set()
with open(m4_filename) as m4_f:
for l in m4_f:
# ......omitted
return overlap_data, contained_reads
overlap_data, contained_reads = get_overlap_data(inputfile) #This line always gave error
......
but I always got error as:
Traceback (most recent call last):
File "learnpython01.py", line 123, in <module>
overlap_data, contained_reads = get_overlap_data(inputfile)
NameError: name 'inputfile' is not defined
I was wondering what the right way it is to pass filename thru argument in python. Related lines are highlighted in red.
Thanks a lot!
With python, error debuging starts at the bottom - with the 'last' error found
Also, to parse options, you should loop through the arguments, and use a case statement to identify the current option name 'opt' (which was retrieved from arg[v]).
Have a look at: info getopt and continue reading (PGDN).
Also checkout man getopt , to get a possible location for code Examples.
Note also that inputfile is only defined if a -i inputfile option is present on the command line.
Maybe you want to define it with a default value in case that option is not present. Or, if there is no reasonable default, print an error message and exit if no -i option was found while parsing the options.
Could not find examples on handling file I/O stream.
I have difficulty to understand string[file] I/O stream here. In the example code, the function prototype is def get_overlap_data(m4_filename):
and, calling of the function is by overlap_data, contained_reads = get_overlap_data(inputfile)
where inputfile = arg from argument parsing.
I am not sure what I have missed among the connections, if any stream is involved.
Thanks any way!