0

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?

3
  • Why? do you "really" want to do imports like this? Commented Jun 20, 2012 at 17:37
  • So I can easily add the modules by putting their classes in the jobs directory. Commented Jun 20, 2012 at 17:38
  • This is very similar to Dynamic module import in Python. And as Ashwini Chaudhary explains below, you are probably simply missing an __init__.py file in your jobs folder to make it a package. Commented Jun 20, 2012 at 17:51

2 Answers 2

2

first of all create a __init__.py file inside jobs folder, to make this jobs.jobs1 thing work.

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.