python - Python 3 中导入路径的问题

标签 python python-import

我对 Python 3 中的 import 语句有疑问。我正在阅读一本书(Python 3 面向对象),并且具有以下结构:

parent_directory/
       main.py
       ecommerce/
             __init__.py
             database.py
             products.py
             payments/
                    __init__.py
                    paypal.py
                    authorizenet.py

在 paypal.py 中,我尝试使用 database.py 中的 Database 类。所以我尝试了这个:

from ecommerce.database import Database

我收到此错误:

ImportError: No module named 'ecommerce'

所以我尝试使用这两个导入语句:

from .ecommerce.database import Database

from ..ecommerce.database import Database

我收到此错误:

SystemError: Parent module '' not loaded, cannot perform relative import

我做错了什么或遗漏了什么?

感谢您的宝贵时间!

最佳答案

将您的parent_directory添加到Python的搜索路径。例如这样:

import sys
sys.path.append('/full/path/to/parent_directory')

或者,您可以将 parent_directory 添加到环境变量 PYTHONPATH

关于python - Python 3 中导入路径的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16884601/

相关文章:

python - Python 中的韦尔奇方差分析

python - 如何在python中导入wave库?

python - 如何从不同的文件夹导入模块?

Python 从子文件夹导入

python - 在Python中导入nltk包时出现问题

python - Python学习过程图

Python:当我导入 RandomForestClassifier 时出现 "TypeError: Could not operate with block values"

python - 如何在 python 中使用 urllib2 和 urllib 制作一个自动登录到我的 wordpress 博客的脚本?

python - 这是在 Python 中运行 shell 脚本的正确方法吗?

python - Mac OS 上 setproctitle 的导入问题,