Python passing filename through argument


 
Thread Tools Search this Thread
Top Forums Programming Python passing filename through argument
# 1  
Old 08-10-2015
Python passing filename through argument

Hello,
A python beginner question on passing filename thru argument. My code is:

Code:
#!/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:
Code:
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!
# 2  
Old 08-10-2015
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.

Hope this helps
# 3  
Old 08-10-2015
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.
# 4  
Old 08-10-2015
What I expected to have the script working in following command line:
Code:
python learnpython01.py -i infile -o outdir -c 500 -e 2

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)
whereinputfile = arg from argument parsing.
I am not sure what I have missed among the connections, if any stream is involved.
Thanks any way!

Last edited by yifangt; 08-10-2015 at 06:17 PM..
# 5  
Old 10-27-2015
The inputfile name is defined inside the function main, so it is out of scope when you're calling
Code:
overlap_data, contained_reads = get_overlap_data(inputfile)

, so you could just call get_overlap_data from inside of main, after handling all the args.
# 6  
Old 11-06-2015
I regret posting this naive questions before I read the book(s). After some more reading and found out one solution:
Code:
overlap_data, contained_reads = get_overlap_data(sys.argv[1])

Need more about getopt() and argparse (as Aia pointed out below) in python.
Thanks to all who replied.

Last edited by yifangt; 12-22-2015 at 01:44 PM..
# 7  
Old 11-07-2015
Try to learn about argparse instead of getopt.
Some documentation why getopt or optparse might not be the right solution.
This User Gave Thanks to Aia For This Post:
Login or Register to Ask a Question

Previous Thread | Next Thread

10 More Discussions You Might Find Interesting

1. UNIX for Beginners Questions & Answers

Passing a second argument

I am trying to pass a second argument like so: if ] then export ARG2=$2 else message "Second argument not specified: USAGE - $PROGRAM_NAME ARG1 ARG2" checkerror -e 2 -m "Please specify if it is a history or weekly (H or W) extract in the 2nd argument" fi however, it always goes... (4 Replies)
Discussion started by: MIA651
4 Replies

2. Shell Programming and Scripting

**python : passing list as argument and updating in definition

In the below python code.. Could anyone please let me know why the name(variable) is getting modified if I update the kargs variable in the definition, def f( kargs): kargs.extend() print ("In function :",kargs) name = f(name) print("Outside function :",name) Output ... (5 Replies)
Discussion started by: scriptscript
5 Replies

3. Shell Programming and Scripting

Argument passing

How to pass the alphabet character as a argument in case and in if block? ex: c=$1 if a-z ]] then echo "alphabet" case $1 in a-z) echo "the value is a alphabet" edit by bakunin: please use CODE-tags. We REALLY mean it. (9 Replies)
Discussion started by: Roozo
9 Replies

4. Shell Programming and Scripting

Help with passing argument

Hi, I have a script that is scheduled with cron and runs every night. The cron part looks like this: 00 20 * * 0,1,2,3,4,5,6 /usr/local/bin/BACKUP TBTARM HOT DELETE My issue is with the 3rd parameter. Somewhere in the script, i want to tell the script to delete some files if the 3rd... (7 Replies)
Discussion started by: dollypee
7 Replies

5. Shell Programming and Scripting

passing argument in script?

hi, I want to implement some function to perform following task if ; then $TEXT = "Data_0" else $TEXT = $1 fi if ; then $Lines = 45 else $Lines = $2 fi Kindly suggest, thanks (11 Replies)
Discussion started by: nrjrasaxena
11 Replies

6. Programming

Passing argument to command in C

Hello all, New to C and I'm trying to write a program which can run a unix command. Would like to have the option of giving the user the ability to enter arguments e.g for "ls" be able to run "ls -l". I would appreciate any help. Thanks #include <stdio.h> #include <unistd.h> #include... (3 Replies)
Discussion started by: effizy
3 Replies

7. Shell Programming and Scripting

Help with Passing argument and testing

Hi all First of all thanks for everyone to read by doubt.Am beginner in shell scripting Following are my doubts i have to pass an argument to shellscript how can i do that second i have to test the argument and shows error when nothing is passes third i have to match exact argument... (3 Replies)
Discussion started by: zeebala1981
3 Replies

8. Shell Programming and Scripting

passing Argument

Hi All, i have script like below.. echo "1) first option" echo "" echo "2) second option" echo "" echo "*) please enter the correct option" read select case $select in 1) echo "first option selected" ;; 2) echo "second option selected" ;; *) echo "please enter the correct... (4 Replies)
Discussion started by: Shahul
4 Replies

9. Shell Programming and Scripting

Problem in argument passing

Hell all, i have a problem in argument passing. print() { a=$1 b=$2 c=$3 echo $a echo $b echo $c } x="1 2 3" y="4 5 6" z="7 8 9" print $x $y $z. (4 Replies)
Discussion started by: tsaravanan
4 Replies

10. UNIX for Dummies Questions & Answers

pass argument to a filename

How can I use the value of an argument as a filename? Example: The argument for a process is 999. I would like the output of the process to be placed in a file called 999. I have tried using $$1, but that only assigns a unigue number. thanks JP (1 Reply)
Discussion started by: jpprial
1 Replies
Login or Register to Ask a Question