building string for __import__()

Adrian Eyre a.eyre at optichrome.com
Fri Dec 17 05:54:15 EST 1999


> my problem was that the variable that I built up with:
>
> [snip]
>
> would give me the import error but just typing it manually into the
> interpreter would work fine. I'll try the . notation.

If it works by hand, try somthing like:

dirdata = {
    'somewhere':   '0',
    'foo':         '1',
    'flub':        '2'
}

filename =  "/mnt/somewhere" + dirdata['somewhere'] + \
        "/foo" + dirdata['foo'] \
        "/flub" + dirdata['flub'] \
        "/TARGET"

expected_filename = "/typing/in/the/path/by/hand/did/it/TARGET"

if filename != expected_filename:
	raise "Pah, I've screwed up somewhere"

c = __import__(filename)



Using the import notation will also have different behaviour depending
on the current working directory when you run the script. Python adds
. to the PYTHONPATH IIRC.

> I'm happy enough with execfile and was just curious about what I was
> doing wrong with __import__

Be aware that execfile is slightly different in that is runs the
script in the __main__ namespace, rather than importing it.

--------------------------------------------
Adrian Eyre <mailto:a.eyre at optichrome.com>
Optichrome Computer Solutions Ltd
Maybury Road, Woking, Surrey, GU21 5HX, UK
Tel: +44 1483 740 233  Fax: +44 1483 760 644
http://www.optichrome.com 
--------------------------------------------





More information about the Python-list mailing list