O.K., I’m coming from Perl to Python and I don’t have much experience in Python so this may seem rather obvious to everyone who’s more experienced with Python.
Anyway, I’m simply loading a configuration file and then, as a self-test, printing the values that are loaded. The code is below:
#!/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'
The error I’m encountering is:
Traceback (most recent call last):
File "./runPipeline.py", line 30, in <module>
for key, value in confDict.iteritems():
NameError: name 'confDict' is not defined
Which I’m interpreting as the name “confDict” has gone out of scope. I don’t understand why it’s gone out of scope.
Your
main()function has it’s own scope – not only that, but you are never calling it.I would suggest you return
confDictfrom your function, and then doconfDict = main()in your running block – or, if you are not going to use yourmain()function in more than one place, just put it straight down, don’t bother with the function.