【问题标题】:How to import a module, which imports another module, from two different folders inside a package如何从包内的两个不同文件夹中导入一个模块,该模块导入另一个模块
【发布时间】:2021-04-20 09:39:11
【问题描述】:

假设我有一个具有以下结构的 python 包:

folder1
   __init__.py
   main.py
   subfolder1
      __init__.py
      submain.py
      subagent.py (contains class Agent)
      subnetwork.py (contains class Network)

subagent.py 文件中,我导入 Network 类,在 main.pysubmain.py 中,我导入 Agent 类。我希望能够从main.pysubmain.py 启动我的程序。但是,这会导致subagent.py 文件出现问题。如果我从main.py 开始,我必须像这样在subagent.py 中编写导入:

from subfolder1.subnetwork import Network 

但是,如果我从 submain.py 开始,我必须像这样在 subagent.py 中编写导入:

from subnetwork import Network 

有没有优雅的解决方案来解决这个问题?

【问题讨论】:

    标签: python python-3.x python-module python-packaging


    【解决方案1】:

    您可以使用 try except 块来导入两种方式

    try:
        from subnetwork import Network
    except ModuleNotFoundError:
        from subfolder1.subnetwork import Network 
    

    【讨论】:

      【解决方案2】:

      改变工作目录?

      import os
      
      if __name__ == "__main__":  # Only change the working directory if the file is run directly
          os.chdir('..') # Move up a level so that it is the same as main
      # now run the imports
      

      【讨论】:

        【解决方案3】:

        使用绝对导入,即以folder1 开头:from folder1 import ...import folder1。像这样调用你的 mainspython -m folder1.mainpython -m folder1.subfolder1.submain

        【讨论】:

          猜你喜欢
          • 2022-12-10
          • 1970-01-01
          • 2020-06-22
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-01-15
          • 1970-01-01
          • 2020-05-18
          相关资源
          最近更新 更多