为什么这个变量不可见?

2024-09-29 19:27:45 发布

您现在位置:Python中文网/ 问答频道 /正文

好吧,我是从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'

我遇到的错误是:

^{pr2}$

我把它解释为“confDict”这个名字已经超出了范围。我不明白为什么会超出范围。在


Tags: keyimportselflogyamlhomedatetimemain
3条回答

confDict对main是本地的,在python中,函数防御依赖于缩进。因此,当您试图在if语句中访问它时,函数作用域就结束了,因为main已经结束。(见缩进)

您的main()函数有它自己的作用域-不仅如此,而且您永远不会调用它。在

我建议您从函数中返回confDict,然后在运行块中执行confDict = main()-或者,如果您不打算在多个地方使用main()函数,只需将其直接放下来,不必为函数操心。在

变量confDict是在函数main()内定义的,因此它是该函数的局部变量。(顺便说一下,你甚至不打电话给main()。)

您可能希望将for循环从脚本的末尾移到main()函数的末尾,并在脚本末尾调用main()。在

相关问题 更多 >

    热门问题