【问题标题】:Python import from paths从路径导入 Python
【发布时间】:2013-04-16 01:00:58
【问题描述】:

我正在为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 添加新文件时,它们仍然是干净的。

【问题讨论】:

    标签: python import path package sys


    【解决方案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
             /...
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-11-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多