为什么这个变量不可见?

phi*_*ogg 0 python scope

好的,我是从Perl转到Python而且我没有太多的Python经验,所以对于那些对Python更有经验的人来说,这似乎相当明显.

无论如何,我只是加载配置文件然后,作为自检,打印加载的值.代码如下:

#!/home/y/bin/python2.7
import logging
import sys
import datetime
import yaml

def main(self):
    #initialize the logger
    logger = logging.getLogger(self.granularity)
    log_fh = logging.FileHandler(filename='/home/logs/pipelineTest/pipelineTest' + datetime.datetime.now().strftime('%Y%m%d_%H%M')  + '.log', mode='w')
    logger.addHandler(log_fh)
    logger.setLevel(logging.INFO)
    formatter = logging.Formatter('%(asctime)-6s: %(name)s - %(levelname)s - %(message)s')
    log_fh.setFormatter(formatter)

    #read configuration file
    if sys.argv[1]:
        ymlFH = open(sys.argv[1])
    else:
        ymFH = open('/home/conf/pipelineTest/runPipeline.yml')

    confDict = yaml.load(ymlFH)

if __name__ == '__main__':
    #self-test code
    for key, value in confDict.iteritems():
      print 'Key is: ' + key + '\n'
      print 'value is: ' + confDict[key] + '\n'
Run Code Online (Sandbox Code Playgroud)

我遇到的错误是:

Traceback (most recent call last):
  File "./runPipeline.py", line 30, in <module>
    for key, value in confDict.iteritems():
NameError: name 'confDict' is not defined
Run Code Online (Sandbox Code Playgroud)

我正在解释为"confDict"的名称已超出范围.我不明白为什么它超出了范围.

Gar*_*tty 6

你的main()功能有它自己的范围 - 不仅如此,你永远不会调用它.

我建议你confDict从你的功能返回,然后confDict = main()在你的运行块中做- 或者,如果你不打算main()在多个地方使用你的功能,只需直接放下,不要打扰功能.