这个问题之前也困扰过,挺有趣。我们用 uswgi 启动 python 应用的,启动时”自动“对应的业务模块。
对每个模块约定文件结构,比如直接是
xxx.py 或者子目录且入口类文件名与子目录名称一致(当然也可以约定其他的)
<pre><code>
## import apps/目录下所有应用
def auto_add_route():
excludes = ".svn common"
routes = []
for f in os.listdir(os.getcwd()): ## the same dir with
gops.py if f in excludes:
continue
importstr = ""
fn = f
ispkg = True
if os.path.isdir(f):
importstr = "from %s import %s" %(f, f)
else:
ispkg = False
if f.endswith('.py'):
fn, fe = f.split('.')
importstr = "import %s" %fn
if len(importstr) == 0:
continue
try:
exec importstr
except ImportError:
print "[ERROR] import failed, [%s]" %importstr
pass
## add route
r = "/myproject/apps/" + fn
classname = fn
mod = ""
try:
mod = __import__(classname, None, None, [''])
except ImportError:
print "[ERROR] import failed, [%s]" % classname
pass
if ispkg:
mod = getattr(mod, classname, None)
inst = getattr(mod, "app", None)
routes.append(r)
routes.append(inst)
return routes
urls = tuple(auto_add_route())
app = web.application(urls, globals())
application = app.wsgifunc()
if __name__== "__main__":
app.run()
</code></pre>