开发者

python: simple way to input python data from file

开发者 https://www.devze.com 2023-04-07 10:23 出处:网络
In a shell script one might do something like: myvar=\'default_value\' source myfile.sh echo $myvar where myfile.sh is something like:

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.

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")
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号