无法从其他软件包导入模块 [英] Unable to import module from another package

查看:76
本文介绍了无法从其他软件包导入模块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的目录结构

conf
    __init__.py
    settings.py
    abc.conf
    def.conf
src
    main.py
    xyz.py

src我选择不制作软件包,而是选择常规文件夹. 我试图在main.py中导入settings.py文件,并使用命令python3 main.py

src I chose not to make a package but a regular folder. I am trying to import the settings.py file in the main.py and executing the whole thing with the command python3 main.py

我在main.py中的导入语句:import conf.settings

My import statement in main.py : import conf.settings

我遇到的错误是No module named conf.settings,我无法理解.

The error I'm getting is No module named conf.settings and I can't get my head around it.

python是否无法将conf识别为软件包?包中是否可以包含.py文件以外的文件(在我的情况下为.conf文件)

Is python failing to recognize conf as a package? Can packages contain files other than .py files (.conf files in my case)

推荐答案

导入python时搜索当前目录和sys.path.由于您的main.py位于src文件夹中,因此无法看到conf软件包文件夹.幸运的是,您可以在运行时更新sys.path.

When importing python search current directory and the sys.path. Since your main.py is in src folder it cannot see the conf package folder. Luckily you could update sys.path at runtime.

root
     conf
        __init__.py
        settings.py
     src
        main.py

因此,您可以在导入conf模块之前从main.py附加sys.path.尝试以下操作:

So you could append sys.path from main.py before importing conf module. Try following:

# main.py
import os, sys
sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))

from conf import settings
...


另一种方法是直接更新PYTHONPATH并将路径添加到脚本根目录.


The other way is to update PYTHONPATH directly and add path to your script root directory.

这篇关于无法从其他软件包导入模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆