Skip to main content
 首页 » 编程设计

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

2024年11月01日7Free-Thinker

我在使用 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 中的数据库类。所以我尝试了这个:

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。