In a shell script one might do something like:
myvar='default_value'
source myfile.sh
echo $myvar
where myfile.sh is something like:
echo "myvar='special_value'" > myfile.sh
I know several “safe” ways of doing this in python, but the only way I can think of getting similar behaviour in Python (albeit ugly and unsafe) is the following:
myvar = 'default_value'
myimport = 'from %s import *' % 'myfile'
exec(myimport)
print(myvar)
where myfile.py is in ./ and looks like:
myvar = 'special_value'
I guess I would be happiest doing something like:
m.myvar = 'default_value'
m.update(__import__(myimport))
and have the objects in m updated. I can’t think of an easy way of doing this without writing something to loop over the objects.
There are two ways to look at this question.
and
If your question is the first; then the most obvious answer is to use the
ConfigParsermodule:Which would read a value from a file that looks like a normal INI style config:
For the second option, when you really want to give full power of python to a configuration (which is rare, but sometimes necessary), You probably don’t want to use
import, instead you should useexecfile:Which in turn will read from a python script; it will read the global variable
myvarno matter how the script derives it: