1

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.

1
  • What's wrong with just import myfile then myvar = myfile.myvar or from myfile import myvar? You need to explain your use case and why that doesn't work. Commented Sep 26, 2011 at 15:45

1 Answer 1

4

There are two ways to look at this question.

How can I read key-value pairs in python? Is there a standard way to do this?

and

How can I give full expressive power to a configuration script?

If your question is the first; then the most obvious answer is to use the ConfigParser module:

from ConfigParser import RawConfigParser
parser = RawConfigParser({"myvar": "default_value"}) # Never use ConfigParser.ConfigParser!
parser.read("my_config")
myvar = parser.get("mysection", "myvar")

Which would read a value from a file that looks like a normal INI style config:

# You can use comments
[mysection]
myvar = special_value

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 use execfile:

config = {}
execfile("my_config", config)
myvar = config.get("myvar", "default_value")

Which in turn will read from a python script; it will read the global variable myvar no matter how the script derives it:

import random
myvar = random.choice("special_value", "another_value")
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.