Python从路径导入

时间:2013-04-23 00:04:25

标签: python import path package sys

我正在使用python中的一个项目开发这种结构:

 main.py      #must get all the classes from /handlers
 jhpy.py
 handlers/    #files must import jhpy without making meth code in the a, b, ... files
         /a.py
         /b.py
         /...
 entities/    # files in handlers may need these. foo, bar, ... must import jhpy without making creepy code
         /foo.py
         /bar.py
         /...

主要目标是使所有这些提到的东西都能正常工作,而不必在每个文件中执行sys.blah blah。重点是,不要让a,b,foo,bar,......有这么可怕的代码。

有什么想法吗?我很确定我必须做更多的文件。也许我需要添加__init__.py,如果是这样,我应该在这些文件中写什么?这些“额外”文件应该执行脏工作,这样当我将新文件添加到/handlers/entities时,它们仍然保持干净。

1 个答案:

答案 0 :(得分:1)

您要用作模块的所有目录都应包含名为 init .py

的文件

您的项目结构如下:

main.py      #must get all the classes from /handlers
jhpy.py
handlers/  
         /__init__.py
         /a.py
         /b.py
         /...
 entities/   
         /__init__.py
         /foo.py
         /bar.py
         /...
相关问题