ms_student
ms_student

Reputation: 21

NameError: name 'n' is not defined in python script

I'm trying to run a python script that is optimized to work with python 2.7:

 #!/usr/bin/env python

import sys,getopt,os

SplitInput_string = """#!/bin/bash
#BSUB -J SplitInput[1-%numSamples%]
#BSUB -o Logs/SplitInput-Out-%I.out
#BSUB -e Logs/SplitInput-Err-%I.err
#BSUB -q week
#BSUB -W 23:58
echo Date: `date`
t1=`date +%s`
sleep ${LSB_JOBINDEX}
python LSFScripts/array_merge.py -r ${LSB_JOBINDEX} -i %input% -o original_reads/
[ $? -eq 0 ] || echo 'JOB FAILURE: $?'
echo Date: `date`
t2=`date +%s`
tdiff=`echo 'scale=3;('$t2'-'$t1')/3600' | bc`
echo 'Total time:  '$tdiff' hours'
"""

help_message = "usage example: python setupDirs.py -i /path/to/reads/ -n numberOfSamples"
if __name__ == "__main__":
    try:
        opts, args = getopt.getopt(sys.argv[1:], 'hi:n:', ["inputdir="])
    except:
        print help_message
        sys.exit(2)
    for opt, arg in opts:
        if opt in ('-h', '--help'):
            print help_message
            sys.exit()
        elif opt in ('-i', '--inputdir'):
            inputdir = arg
            if inputdir[-1] != '/':
                inputdir += '/'
        elif opt in ('-n'):
            n = arg
    for dir in ['Logs', 'original_reads', 'hashed_reads', 'cluster_vectors', 'read_partitions']:
        os.system('mkdir %s' % (dir))
    f = open('LSFScripts/SplitInput_ArrayJob.q', 'w')
    f.write(SplitInput_string.replace('%numSamples%', n).replace('%input%', inputdir))
    f.close()

But I keep getting this error message:

line 42, in <module>
f.write(SplitInput_string.replace('%numSamples%', n).replace('%input%', inputdir))
NameError: name 'n' is not defined

Any advice would be appreciated!

Upvotes: 0

Views: 1628

Answers (2)

arewm
arewm

Reputation: 649

n is not defined in all code paths. It is only defined if you follow the path:

elif opt in ('-n'):

Define m at a higher scope (i.e. before the for loop) with a default value if you want to use it afterwards.

n = #default value
for opt, arg in opts:
    # ...

If you want to parse arguments, I highly recommend using the argparse package. There is a little bit of a learning curve, but you can very robustly generate the necessary usage.

Upvotes: 1

dot.Py
dot.Py

Reputation: 5157

You must assign a value to n before entering the loop.

if __name__ == "__main__":
    try:
        opts, args = getopt.getopt(sys.argv[1:],'hi:n:',["inputdir="])
    except:
        print help_message
        sys.exit(2)

    n = ""

    for opt, arg in opts:

    etc...

Upvotes: 1

Related Questions