how can I import a module without using pythonpath?

P

Phd

Hi,

I'm using python 2.2, I want to import a module by referring to its
relative location. The reason for this is that there is another module
with the same name that's already in pythonpath( not my decision, but I
got to work around it, bummer). So is there any easy way to do it?

something like
import module "from this location"


Thanks!
 
D

Doug Holton

Phd said:
Hi,

I'm using python 2.2, I want to import a module by referring to its
relative location. The reason for this is that there is another module
with the same name that's already in pythonpath( not my decision, but I
got to work around it, bummer). So is there any easy way to do it?

import sys, os
sys.path.insert(0,os.path.abspath("relative path"))
import module
sys.path.remove(os.path.abspath("relative path"))
 
P

Phd

Nice, thanks so much!



Doug said:
import sys, os
sys.path.insert(0,os.path.abspath("relative path"))
import module
sys.path.remove(os.path.abspath("relative path"))
 
F

Fredrik Lundh

Doug said:
import sys, os
sys.path.insert(0,os.path.abspath("relative path"))
import module
sys.path.remove(os.path.abspath("relative path"))

a try-finally clause is a pretty good idea, in this case.

you might also wish to store the calculated path, in case the module
changes the current directory. or store the original sys.path, in case
the module messes with the path but shouldn't. (on the other hand, if
the module is nice and well behaved, you can replace the last line with
del sys.path[0]...)

</F>
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,535
Members
45,007
Latest member
obedient dusk

Latest Threads

Top