importing / loading a module / class dynamically
hg
hg at nospam.org
Fri Jan 5 04:57:28 EST 2007
Laszlo Nagy wrote:
>
>> .../.../../plugin/name1/name1.py
>> ....
>> .../.../../plugin/namen/namen.py
>>
>>
>> I block at the beginning and tried this (test.py is a real file)
>>
>>>>> s = 'test.py'
>>>>> eval ('import ' + s)
>>>>>
> import test.py # This is invalid
> import test # This MAY be valid
> import name1.name1 # Most probably this is what you want if you have the
> aforementioned directory stucture
> from name1 import name1 # Or this?
>
> You must also:
>
> 1. Have the 'plugin' dir in your sys.path
> 2. Have at least an empty plugin/name1/__init__.py file
>
> Another alternative is to have plugins/__init__.py and do something like:
>
> from plugins.name1 import name1
>
> You should not overcomplicate things anyway. If you do not need these
> name1...namen directories for sure, then just drop them.
>
> Hint: try this (untested)
>
> import os
> fnames = os.listdir('plugins')
> for fname in fnames:
> if os.path.isdir(fname):
> root,ext = os.path.splitext(fname)
> cmd = "from plugins.%s import %s" % (root,root)
> print "I should eval this:",cmd
>
> Best,
>
> Laszlo
>
>
>> Traceback (most recent call last):
>> File "<pyshell#1>", line 1, in -toplevel-
>> eval ('import ' + s)
>> File "<string>", line 1
>> import test.py
>>
Thanks,
What I am doing is adding plugin support to PyCrust ... so I'm looking for a
mechanism where anyone can develop a plugin and have it loaded by pycrust.
the .py was a typo
why the "...Have at least an empty plugin/name1/__init__.py file..." ?
Thanks,
hg
More information about the Python-list
mailing list