好吧,我是从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”这个名字已经超出了范围。我不明白为什么会超出范围。在
confDict对main是本地的,在python中,函数防御依赖于缩进。因此,当您试图在if语句中访问它时,函数作用域就结束了,因为main已经结束。(见缩进)
您的
main()
函数有它自己的作用域-不仅如此,而且您永远不会调用它。在我建议您从函数中返回
confDict
,然后在运行块中执行confDict = main()
-或者,如果您不打算在多个地方使用main()
函数,只需将其直接放下来,不必为函数操心。在变量
confDict
是在函数main()
内定义的,因此它是该函数的局部变量。(顺便说一下,你甚至不打电话给main()
。)您可能希望将for循环从脚本的末尾移到
main()
函数的末尾,并在脚本末尾调用main()
。在相关问题 更多 >
编程相关推荐