Symbolic imports and manipulation of the namespace?

Bengt Richter bokr at oz.net
Tue Mar 26 19:39:51 EST 2002


On Tue, 26 Mar 2002 15:12:09 -0700, VanL <vlindberg at verio.net> wrote:

>Hello,
>
>I was recently solving a problem which required that the config file 
>(just a python file) lie outside of the pythonpath.  Is it possible to 
>do symbolic importation of a module?
>
>For example, I had:
>
># cfgpath is passed in on the command line
>cfgpath = os.path.basename(cfgpath)
>sys.path.insert (0, cfgpath)
>import sc_cfg     #Hardcoded config module name!
>
>
>How do you do this:
>
># cfgpath is passed in on the command line
>cfgpath, cfgfile = os.path.split(cfgpath)
>sys.path.insert (0, cfgpath)
>import cfgfile     #Hardcoded config module name!
>
>So that any file name (ending with .py, of course, but that's another 
>matter) could be the configfile?
>I tried the above, but I got an ImportError (no module named cfgfile)
>
>Thanks,
>
see if help(__import__) helps decide if you need to worry
about default arguments.

 >>> cfgfile = 'xxx.py'
 >>> import cfgfile
 Traceback (most recent call last):
   File "<stdin>", line 1, in ?
 ImportError: No module named cfgfile
                              ^^^^^^^---Notice
 >>> __import__(cfgfile)
                ^^^^^^^--Notice
 Traceback (most recent call last):
   File "<stdin>", line 1, in ?
 ImportError: No module named xxx.py
                              ^^^^^^---Notice
 
Looks like you may need to drop the '.py' if your cfgpath has one,
or it will think package syntax. Also you have to do something
with the __import__() return value, like maybe (untested)

  cfgmodule = __import__(cfgfile.split('.py')[0])

I haven't used this, so it's theory for you to test ;-)

Regards,
Bengt Richter




More information about the Python-list mailing list