Reputation: 10969
My project layout looks like:
run.py
jobs/
job1.py
job2.py
job1.py
is pretty basic:
class job1():
def __init__(self):
print 'yo'
In run.py, I have:
name = 'job1'
classname = 'jobs.%s' % name
__import__(classname)
Which obviously does not work:
Traceback (most recent call last):
File "run.py", line 5, in <module>
__import__(classname)
ImportError: No module named jobs.job1
What is the best way to import the modules in this manner?
Upvotes: 0
Views: 131
Reputation: 251116
first of all create a __init__.py
file inside jobs folder, to make this jobs.jobs1
thing work.
Upvotes: 2
Reputation: 34718
Add this to your __init__.py
in jobs
directory
import os
jobs = {}
for module in (name for name in os.listdir(".") if name.endswith(".py")):
jobs[module] = __import__(module)
Then just use it like this
from jobs import jobs
Upvotes: 1