Importing at runtime

Mike Meyer mwm at
Tue Oct 25 07:25:25 CEST 2005

"David Poundall" <david at> writes:
> I have several .py files in a directory that I would like to import at
> run time.  Each file contains a state machine that requires to be run
> in its own thread.

Imports happen at run time. Beware starting threads in the code run at
import time in each module, though - there are some nasty bugs lurking
there. Instead, start the threads in functions invoked from the main

> The first problem I have is how can I import the code in all of the .py
> files without knowing the file names in advance.
> Can this be done ??

Yes. Use the __import__ builtin.

Mike Meyer <mwm at>
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.

More information about the Python-list mailing list