Importing at runtime

D

David Poundall

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.

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 ??

TIA
 
J

James Stroud

exec "import something"

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.

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 ??

TIA

--
James Stroud
UCLA-DOE Institute for Genomics and Proteomics
Box 951570
Los Angeles, CA 90095

http://www.jamesstroud.com/
 
D

David Poundall

Thanks James, just after I posted I stumbled across the execfile
command. Looks like with 'exec' and 'execfile' I should be able to do
what I want.

What an elegant language.
 
M

Mike Meyer

David Poundall said:
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
routine.
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
 
D

David Poundall

Devan, would ...

__import__(name) for name in module_names

have worked just as well - without the equate to modules? or is the
modules list required as a hook for the imports ?
 
D

David Poundall

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
routine.

I have run into trouble trying to do that before. Thanks for the
reminder Mike.
 

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

No members online now.

Forum statistics

Threads
474,269
Messages
2,571,338
Members
48,025
Latest member
Rigor4

Latest Threads

Top