python - 有没有更好的方法在 python 项目中设置 sys.path.append ?

标签 python python-import

我有一个简单的 python 项目,其目录结构如下:

sample-project/
main/
    config/
        config.yaml
    docker/
        Dockerfile
    tests/
        __init__.py
        sometests.py
    config.py
    run.py
    __init__.py
requirements.txt
README.rst

config.py文件中,我有:

import yaml


class Config:

def __init__(self):
    with open("config/config.yaml", 'r') as ymlfile:
        cfg = yaml.load(ymlfile)

        self.host = cfg["mysql"]["host"]
        self.database = cfg["mysql"]["database"]
        self.user = cfg["mysql"]["user"]
        self.password = cfg["mysql"]["password"]


my_config = Config()

run.py文件中,我有一个导入语句,如下所示:

from main.config import my_config

当我使用命令行运行时:python3.5 run.py,我收到错误:

from main.config import my_config

ImportError: No module named 'main'

但是当我在 run.py 导入中添加它时,它可以工作:

import sys
sys.path.append('/home/tomas/sample-project/')

有没有比给出绝对路径或任何其他方式更好的方法来使其工作?请举一些例子:)

最佳答案

一般来说,永远不要在程序中触摸sys.path

由于 main/ (不是最好的名称)包含 __init__.py,我们将其视为一个包,所以让我们 make it runnable as one 。这样导入就会被正确考虑。

添加main/__main__.py,例如

from main.run import run

if __name__ == "__main__":
   run()

然后运行您的应用程序

python -m main

而不是

python main/main.py

关于python - 有没有更好的方法在 python 项目中设置 sys.path.append ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59562426/

相关文章:

python - 如何在不初始化 GPU 的情况下使我的包可导入

python - 我如何过滤 Pandas 数据框并根据其他列和其他条件仅保留行

python - 如何在bertopic建模中获得主题概率矩阵

Python Unicode解码错误: 'ascii' codec can't decode byte 0xe2 ordinal not in range(128)

Python 导入错误 : cannot import name XXXX

python-3.x - Python opencv Aruco "No module named ' cv2.aruco'”

python - 如何在tensorflow中实现提前停止

python - 如何从字符串 'long' 创建一个 numpy dtype?

python - 如何模拟导入

Python - 导入错误 : attempted relative import with no known parent package