import via pathname

Steven Bethard steven.bethard at gmail.com
Mon Jun 20 10:35:29 EDT 2005


passion_to_be_free at hotmail.com wrote:
> I know this is wrong syntax, but I think it demonstrates what I'm
> trying to do:
> 
> import myModule path = /modules/myModule
> import myModule2 path = /modules/myModule2
> 
> Something like that.  Is it possible?

I would put your additional modules into a 'modules' directory with an 
__init__.py.  For example:

py> os.listdir('.')
['modules']
py> os.listdir('modules')
['my_module1.py', 'my_module2.py', '__init__.py']
py> file('modules/__init__.py').read()
''
py> file('modules/my_module1.py').read()
'name = "module1"\n'
py> file('modules/my_module2.py').read()
'name = "module2"\n'

Then, if you place your python script in the same directory as the 
'modules' directory, you can simply import the additional modules from 
the 'modules' package:

py> import modules.my_module1 as module1
py> module1.name
'module1'
py> import modules.my_module2 as module2
py> module2.name
'module2'

Note that the 'modules' package needs to be at the same directory level 
as your Python module.  If you want your 'modules' directory in a 
different location, you may want to go the way of Thomas Güttler's 
suggestion and modify sys.path.  But I probably wouldn't if you don't 
have to.

STeVe



More information about the Python-list mailing list