我对 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/