【问题标题】:Python Project Structure, ImportsPython 项目结构,导入
【发布时间】:2016-07-11 15:33:20
【问题描述】:

我有以下 python 项目设置:

/project
    /doc
    /config
        some_config.json
    /src
        /folderA
            __init__.py
            Databaseconnection.py
            ...
        /folderB
            __init__.py
            Calculator.py
            ...
        /main
            __init__.py
            Main.py
            ...
        /test
            __init__.py
            AnImportantTest.py
        __init__.py
    .gitignore
    README.md
    requirements.txt

Main.py 是调用所有其他模块的“可执行文件”(或者更确切地说是模块)。所有__init__.py 文件都是空的。 Main.py 中的 import 语句应该是什么样子的? 我还看到了 this,但这不是很有帮助:

# Main.py

import sys
sys.path.insert(0,'../..')

from folderA.Databaseconnection import *      # not working
from src.folderA.Databaseconnection import *  # not working

谢谢。

【问题讨论】:

  • 我会将Main.py(应该是小写字母)移动到/src,这将简化导入,并将/tests 放在/project 下的单独目录中。就目前而言,您需要 .. 在您的 imports 中“向上”一个目录,而不是破解路径。

标签: python


【解决方案1】:

使用sys.path.insert() 为python 提供了另一个目录来查看要导入的模块。目录../../ 添加了文件夹/project,但这不是模块所在的位置。改用这个:

# Main.py

import sys
sys.path.insert(0,'../') # /src

from folderA.Databaseconnection import *

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-04-16
    • 2022-01-17
    • 1970-01-01
    • 1970-01-01
    • 2018-11-21
    • 1970-01-01
    • 2016-12-10
    • 1970-01-01
    相关资源
    最近更新 更多