473,734 Members | 2,511 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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.p y 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 9387
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.p y 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.or g> 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...@m ired.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.p y 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(confi gfile):
cfg = {}
syspath = list(sys.path)
try:
sys.path.append (os.path.dirnam e(configfile))
execfile(config file, 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.c omwrote:
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(confi gfile):
return dict(inspect.ge tmembers(__impo rt__(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...@m ired.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.or g> 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
17398
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 simple Python program: # main.py def f() : x = 1 print "x:", x f()
2
1957
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 be filled by the import, e.g. a class like: >>> class MyModuleDict(dict): .... def __setitem__(self,name,val):
16
3112
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() : global math # necessary ?????? else next line generate an error message ?????
2
1478
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 v v = 6
10
1892
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 rather bizzare example that breaks this invariant: can anyone enlighten me as to what is going on? --- test.py --- import imptest execfile('subtest.py', dict(__name__ = 'subtest.py')) --- imptest.py --- print 'Imptest imported'
10
2649
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() filename = t + '-' + t + '-' + t + '.py' import filename
3
1628
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 description and an associated file name and program name. The file name is the name of a .py file (impName) and the program name is the name of a class in that file which I instantiate to run the program (progName). When a menu option is selected, I execute the program like this - imp =...
2
2218
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 I do not want to include in the EXE because they are used for program configuration (similar to the way an INI file is used.) These file may change per installation, so I may need to edit them. Having them wrapped up in the EXE just won't work for my needs. I've used the 'exclude' option to...
0
160
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! Hmm looks like your tmp2.py file is not a module but a whole program. No wonder I could not understand you - I thought that "tmp2.py" is a module, not a program. The answer in this case: if tmp2.py is a program then you should either
0
8946
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8776
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9449
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9310
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9236
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8186
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6735
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4550
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
3261
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

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.