How do I import everything in a subdir?

John Roth newsgroups at jhrothjr.com
Sun Mar 6 05:56:53 EST 2005


"Dfenestr8" <chrisdewinN0SPAM at yahoo.com.au> wrote in message 
news:pan.2005.03.06.05.20.39.304209 at yahoo.com.au...
> Hi.
>
> I have a program which I want a plugin directory for. I figured the way to
> go about that would be to just add a plugin/ dir to sys.path, and import
> everything in it. Then my program can just execute the main() method of
> each imported plugin.
>
> Is that a good way to go about it?
>
> If so, how do I import everything in the plugins dir? The method raises an
> error as you can see.

Read the directory and then use the __import__() method on each
entry that ends in .py, .pyc or .pyo. Filter for duplicates first or you
may be executing a single plugin more than once.

Don't bother with sys.path unless you want your plugins to be
able to import from that directory as well.

John Roth


>
>>>> import sys
>>>> import os
>>>> sys.path.append("plugins")
>>>> ls = os.popen("ls plugins").readlines()
>>>> for x in ls:
> ...     plugs.append(x[0:x.rfind(".py")])
>>>> for x in plugs:
> ...     import x
> ...
> Traceback (most recent call last):
>  File "<stdin>", line 2, in ?
> ImportError: No module named x
> 




More information about the Python-list mailing list