472,328 Members | 1,782 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 472,328 software developers and data experts.

Import and execfile()

I maintain a few configuration files in Python syntax (mainly nested
dicts of ints and strings) and use execfile() to read them back to
Python. This has been working great; it combines the convenience of
pickle with the readability of Python. So far each configuration is
contained in a single standalone file; different configurations are
completely separate files.

Now I'd like to factor out the commonalities of the different
configurations in a master config and specify only the necessary
modifications and additions in each concrete config file. I tried the
simplest thing that could possibly work:

======================
# some_config.py

# master_config.py is in the same directory as some_config.py
from master_config import *

# override non-default options
foo['bar']['baz] = 1
....

======================
# trying to set the configuration:
CFG = {}
execfile('path/to/some_config.py', CFG)

Traceback (most recent call last):
....
ImportError: No module named master_config
I understand why this fails but I'm not sure how to tell execfile() to
set the path accordingly. Any ideas ?

George
Jan 11 '08 #1
5 9090
On Fri, 11 Jan 2008 14:05:11 -0800 (PST) George Sakkis <ge***********@gmail.comwrote:
I maintain a few configuration files in Python syntax (mainly nested
dicts of ints and strings) and use execfile() to read them back to
Python. This has been working great; it combines the convenience of
pickle with the readability of Python. So far each configuration is
contained in a single standalone file; different configurations are
completely separate files.
You know, I've been there before. It's kinda neat, but not something
you really want to put in the hands of most users.

You can make the syntax cleaner by using classes to hold the values
instead of nested dicts, etc. That way you don't have to quote the
names of the values:

class Foo:
bar = 1
baz = 2

The really slick part was that if the config classes line up with the
implementation classes, you can create an instance of the config class
for the implementation object, and it can then change those values to
change it's behavior without changing the defaults other instances
see.
Now I'd like to factor out the commonalities of the different
configurations in a master config and specify only the necessary
modifications and additions in each concrete config file. I tried the
simplest thing that could possibly work:
With classes you factor out the commonality by factoring it into a
base class that the others inherit from.
======================
# some_config.py

# master_config.py is in the same directory as some_config.py
from master_config import *

# override non-default options
foo['bar']['baz] = 1
...

======================
# trying to set the configuration:
CFG = {}
execfile('path/to/some_config.py', CFG)

Traceback (most recent call last):
...
ImportError: No module named master_config
I understand why this fails but I'm not sure how to tell execfile() to
set the path accordingly. Any ideas ?
Manipulate sys.path yourself?

<mike

--
Mike Meyer <mw*@mired.org> http://www.mired.org/consulting.html
Independent Network/Unix/Perforce consultant, email for more information.
Jan 11 '08 #2
On Fri, 11 Jan 2008 14:05:11 -0800 (PST)
George Sakkis <ge***********@gmail.comwrote:
# trying to set the configuration:
CFG = {}
execfile('path/to/some_config.py', CFG)

Traceback (most recent call last):
...
ImportError: No module named master_config
I understand why this fails but I'm not sure how to tell execfile() to
set the path accordingly. Any ideas ?
This might be overly simplistic but you could have a load_config
function which takes the path to the config file and the variable where
to load the config as arguments.

In the load_config function, you could get the directory part of the
config file path, appending it to sys.path, load the config, and then
remove the newly added directory from sys.path.

--
Mitko Haralanov
Jan 12 '08 #3
On Jan 11, 5:24 pm, Mike Meyer <mwm-keyword-python.b4b...@mired.org>
wrote:
On Fri, 11 Jan 2008 14:05:11 -0800 (PST) George Sakkis <george.sak...@gmail.comwrote:
I maintain a few configuration files in Python syntax (mainly nested
dicts of ints and strings) and use execfile() to read them back to
Python. This has been working great; it combines the convenience of
pickle with the readability of Python. So far each configuration is
contained in a single standalone file; different configurations are
completely separate files.

You know, I've been there before. It's kinda neat, but not something
you really want to put in the hands of most users.
Well, I am almost the only user (of the config file, not the
application) and the few others are developers too so that's not an
issue in this case.
You can make the syntax cleaner by using classes to hold the values
instead of nested dicts, etc. That way you don't have to quote the
names of the values:

class Foo:
bar = 1
baz = 2
Actually I am using the dict() constructor instead of literals so it's
as clean as with classes; IMO for nested options it's cleaner than
nested classes:

Env = dict(
PORT = 6789,
KEY = 123456789,
EXE = '/usr/local/lib/myprog',
LD_LIBRARY_PATH = ':'.join([
'/usr/lib',
'/usr/local/lib',
]),
OPTIONS = dict(
n = None,
min = 1,
max = 15000,
)
)

======================
# some_config.py
# master_config.py is in the same directory as some_config.py
from master_config import *
# override non-default options
foo['bar']['baz] = 1
...
======================
# trying to set the configuration:
CFG = {}
execfile('path/to/some_config.py', CFG)
Traceback (most recent call last):
...
ImportError: No module named master_config
I understand why this fails but I'm not sure how to tell execfile() to
set the path accordingly. Any ideas ?

Manipulate sys.path yourself?
That's what Mitko suggested too, and indeed it works:

import sys, os

def setConfig(configfile):
cfg = {}
syspath = list(sys.path)
try:
sys.path.append(os.path.dirname(configfile))
execfile(configfile, cfg)
finally:
sys.path = syspath
return cfg
However this doesn't look very clean to me. Also it's not thread-safe;
guarding it explicitly with a lock would make it even less clean.
Ideally, I'd like to pass a new path to execfile without modifying the
original (even for the few milliseconds that execfile() wlll probably
take). With modules being singletons though, I don't think this is
possible, or is it ?

George
Jan 12 '08 #4
On Jan 11, 6:54 pm, Mitko Haralanov <mi...@qlogic.comwrote:
On Fri, 11 Jan 2008 14:05:11 -0800 (PST)

George Sakkis <george.sak...@gmail.comwrote:
# trying to set the configuration:
CFG = {}
execfile('path/to/some_config.py', CFG)
Traceback (most recent call last):
...
ImportError: No module named master_config
I understand why this fails but I'm not sure how to tell execfile() to
set the path accordingly. Any ideas ?

This might be overly simplistic but you could have a load_config
function which takes the path to the config file and the variable where
to load the config as arguments.

In the load_config function, you could get the directory part of the
config file path, appending it to sys.path, load the config, and then
remove the newly added directory from sys.path.
Thanks, that's basically what I did eventually and it works for my
simple requirements. Another alternative would be to require the
config files to be modules already in the path. In this case setConfig
becomes almost trivial using __import__ instead of execfile():

import inspect
def setConfig(configfile):
return dict(inspect.getmembers(__import__(configfile,
fromlist=True)))

On the downside, the config files cannot be moved around as easily as
with execfile. Also, if placed in directories that are not in the
path, one or more ancestor directories may have to be populated with
(empty) __init__.py files to denote them as Python packages. So
generally speaking, when should execfile be preferred to __import__,
or the other way around ?

George
Jan 12 '08 #5
On Fri, 11 Jan 2008 20:55:07 -0800 (PST) George Sakkis <ge***********@gmail.comwrote:
On Jan 11, 5:24 pm, Mike Meyer <mwm-keyword-python.b4b...@mired.org>
wrote:
On Fri, 11 Jan 2008 14:05:11 -0800 (PST) George Sakkis <george.sak...@gmail.comwrote:
I maintain a few configuration files in Python syntax (mainly nested
dicts of ints and strings) and use execfile() to read them back to
Python. This has been working great; it combines the convenience of
pickle with the readability of Python. So far each configuration is
contained in a single standalone file; different configurations are
completely separate files.
You can make the syntax cleaner by using classes to hold the values
instead of nested dicts, etc. That way you don't have to quote the
names of the values:
class Foo:
bar = 1
baz = 2
Actually I am using the dict() constructor instead of literals so it's
as clean as with classes; IMO for nested options it's cleaner than
nested classes:
Yup, that does that. Wasn't available last time I did this, so...
I understand why this fails but I'm not sure how to tell execfile() to
set the path accordingly. Any ideas ?
Manipulate sys.path yourself?
That's what Mitko suggested too, and indeed it works:
However this doesn't look very clean to me. Also it's not thread-safe;
I don't know that there is a clean solutions. As for not being
thread-safe, I'd suggest that you should have all your configuration
information loaded *before* you start any threads. This makes shutting
down in case you decide there's something wrong in it easier, and in
some cases may prevent inadvertently doing things that shouldn't
oughta be done. In the case where you config files are parsed by the
python interpreter, this goes double because a busted config file
could lead to exceptions, leaving your application in an unknown
state.

<mike
--
Mike Meyer <mw*@mired.org> http://www.mired.org/consulting.html
Independent Network/Unix/Perforce consultant, email for more information.
Jan 12 '08 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
by: Jonathan | last post by:
I'm puzzled by Python's behavior when binding local variables which are introduced within exec() or execfile() statements. First, consider this...
2
by: Fritz Bosch | last post by:
Hi experts Is is possible to import/manipulate a module such that I can supply its __dict__? I want to supply my own dict subclass object to...
16
by: didier.doussaud | last post by:
I have a stange side effect in my project : in my project I need to write "gobal" to use global symbol : .... import math .... def f() :...
2
by: overly.crazy.steve | last post by:
I am seeing something strange with execfile. I've simplified the code to: ########## t.py ########## print "here" v = None def f(): global...
10
by: Michael Abbott | last post by:
It seems to be an invariant of Python (insofar as Python has invariants) that a module is executed at most once in a Python session. I have a...
10
by: leonel.gayard | last post by:
Hi all, I have a script responsible for loading and executing scripts on a daily basis. Something like this: import time t = time.gmtime()...
3
by: Frank Millman | last post by:
Hi all I am writing a business/accounting application. Once a user has logged in they are presented with a menu. Each menu option has a...
2
by: ward.david | last post by:
I am using py2exe to generate an executable so that I can deliver my scripts as a EXE. I have a couple of file that are needed by the program that...
0
by: Laszlo Nagy | last post by:
ohad frand wrote I think that using absolute names DOES solve the problem. import two.tmp2 # This will import tmp2.py in "two" folder for sure!...
0
by: tammygombez | last post by:
Hey fellow JavaFX developers, I'm currently working on a project that involves using a ComboBox in JavaFX, and I've run into a bit of an issue....
0
by: tammygombez | last post by:
Hey everyone! I've been researching gaming laptops lately, and I must say, they can get pretty expensive. However, I've come across some great...
0
by: concettolabs | last post by:
In today's business world, businesses are increasingly turning to PowerApps to develop custom business applications. PowerApps is a powerful tool...
0
better678
by: better678 | last post by:
Question: Discuss your understanding of the Java platform. Is the statement "Java is interpreted" correct? Answer: Java is an object-oriented...
0
by: teenabhardwaj | last post by:
How would one discover a valid source for learning news, comfort, and help for engineering designs? Covering through piles of books takes a lot of...
0
by: Kemmylinns12 | last post by:
Blockchain technology has emerged as a transformative force in the business world, offering unprecedented opportunities for innovation and...
0
by: CD Tom | last post by:
This happens in runtime 2013 and 2016. When a report is run and then closed a toolbar shows up and the only way to get it to go away is to right...
0
by: Matthew3360 | last post by:
Hi there. I have been struggling to find out how to use a variable as my location in my header redirect function. Here is my code. ...
1
by: Matthew3360 | last post by:
Hi, I have a python app that i want to be able to get variables from a php page on my webserver. My python app is on my computer. How would I make it...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.