python modules as user configuration files

Robin Thomas robin.thomas at starmedia.net
Thu Apr 5 16:39:47 EDT 2001


At 07:36 AM 4/6/01 +1200, Graham Guttocks wrote:
>Greetings Python Experts,
>
>For my application, I would like users to have a python module as
>a configuration file to define variables and whatnot.
>
>Is there any way to explicitly import a particular file using its full
>path name?

I would recommend not using "import", which would actually install the 
module in sys.modules and possibly screw up imports of other, legitimate 
modules you have created. Also, importing from a fullpath is not very 
straightforward.

Instead, consider the config file a Python "script", not a module. Your 
program can read in the script, compile it, and execute it in namespaces 
that you define. Here's a brief example:

def load_config(filepath):
     myconfig = {}
     try:
         execfile(filepath, myconfig)
     except:
         print "config file raised an error"
         return {}
     # examine stuff in myconfig, if you want,
     # I left it out
     return myconfig


--
Robin Thomas
Engineering
StarMedia Network, Inc.
robin.thomas at starmedia.net





More information about the Python-list mailing list