NameError:name' n'没有在python脚本中定义

时间:2016-06-29 17:49:41

标签: python

我试图运行经过优化的python脚本以使用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()

但我不断收到此错误消息:

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

任何建议都将不胜感激!

2 个答案:

答案 0 :(得分:1)

n未在所有代码路径中定义。只有在您遵循以下路径时才会定义:

elif opt in ('-n'):

如果您想在之后使用默认值,请在更高的范围(即在for循环之前)定义m

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

如果要解析参数,我强烈建议您使用argparse包。有一点学习曲线,但您可以非常稳健地生成必要的用法。

答案 1 :(得分:1)

在进入循环之前,您必须为let top = topMostController() let alertController = UIAlertController(title: "Location pinned", message: "You've successfully pinned this location, good work!", preferredStyle: UIAlertControllerStyle.Alert) let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.Default) { (result : UIAlertAction) -> Void in print("OK") } alertController.addAction(okAction) self.presentViewController(myAlert, animated: true, completion: nil) top.presentViewController(alertController, animated: true, completion: { _ in }) 分配一个值。

n