0

我的项目布局如下:

run.py
jobs/
   job1.py
   job2.py

job1.py非常基本:

class job1():

    def __init__(self):
        print 'yo'

在 run.py 中,我有:

name = 'job1'
classname = 'jobs.%s' % name
__import__(classname)

这显然不起作用:

Traceback (most recent call last):
  File "run.py", line 5, in <module>
    __import__(classname)
ImportError: No module named jobs.job1

以这种方式导入模块的最佳方法是什么?

4

2 回答 2

2

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

于 2012-06-20T17:39:49.027 回答
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
于 2012-06-20T17:40:22.333 回答