【问题标题】:I want to be able to load class from both root and sub path我希望能够从根路径和子路径加载类
【发布时间】:2017-11-28 17:50:58
【问题描述】:

我有一个问题。

我的python项目路径如下:

代码根 | -code_sub | |- b.py | --c.py -a.py

从 b.py 导入 code_sub 的 c.py。

所以我希望能够从 code_root 和 code_sub 路径加载 b.py。

例如:

code_root>$ python nlp.py

code_root/code_sub>$ python b.py

这里的问题是调用c.py。

b.py 不应该像这样导入 c.py:

# b.py import c

所以我找到了我的解决方案。

如下:

from os.path import dirname curpath = dirname(__file__) if len(curpath) == 0: curpath = '.' c = imp.load_source('c', curpath+'/c.py')

这可行,但它似乎不是最好的解决方案。有没有更标准的 Python 方法可以用来完成同样的事情?

【问题讨论】:

    标签: python python-3.x import


    【解决方案1】:

    我通常将我的项目设置如下,并为我的导入使用完全限定的路径。另外,我强烈建议您使用虚拟环境——然后您可以使用命令“add2virtualenv MyWorkinator, workinator”,这使得导入变得不那么复杂。

       MyWorkinator   (Project level folder)
        |
        - workinator   (All code here)
          |
          - package_a
            |
            - a1.py
            - a2.py
          - package_b
            |
            - b1.py
            - b2.py
          c.py
    

    在 c.py 中:

    import workinator.package_b.b1
    

    在 b2.py 中:

    import workinator.package_a.a1
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-03-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-21
      • 2011-01-26
      • 2018-12-31
      • 1970-01-01
      相关资源
      最近更新 更多