I have various variables I am setting in a bunch of Python files and I want to move them to a config file. While the python config parser library allows me to centralise these variables, it still requires a lot of code in each file to fetch every config setting and assign to a variable.
What I would like to do is minimise the code used to set these variables. So for the below settings.ini I would like to be able to just use something like setVars('QUEUE')
to loop through the section named QUEUE and set variables in the current file with the same name as their key in the settings.ini file. I have tried a few approaches but without success. Is this even possible?
[QUEUE]
queueSrvr = '192.168.0.50'
queuePort = 5672
queueUser = 'guest'
queuePass = 'guest'
[DATABASE]
dbase = 'robotAI'
user = 'root'
passwd = 'Password123'
servr = 'localhost'
Below is one example that IMHO should work.
import configparser
def setVariables(section):
global x
x = "just a test"
config = configparser.ConfigParser()
config.sections()
config.read('/home/lee/Downloads/robotAI4/settings.ini')
data = dict(config.items(section))
for key in data:
print('global ' + key)
exec('global ' + key)
print(key + ' = ' + data[key])
exec(key + ' = ' + data[key])
setVariables('QUEUE')
print (x)
print (queueuser)
But what I get from this is the following output:
global queuesrvr
queuesrvr = '192.168.0.50'
global queueport
queueport = 5672
global queueuser
queueuser = 'guest'
global queuepass
queuepass = 'guest'
just a test
Traceback (most recent call last):
File "Downloads/robotAI4/test.py", line 20, in <module>
print (queueuser)
NameError: name 'queueuser' is not defined
It is quite clearly looping through the values and running the global statements and then setting the values. So why does x have a value outside the function but not queueuser?