我有一个存放客户端代码的文件夹、一个存放服务器代码的文件夹,以及一个存放它们之间共享的代码的文件夹
Proj/
Client/
Client.py
Server/
Server.py
Common/
__init__.py
Common.py
如何从 Server.py 和 Client.py 导入 Common.py?
最佳答案
2014 年 11 月编辑(3 年后):
Python 2.6 和 3.x 支持适当的相对导入,您可以避免做任何不合时宜的事情。使用这种方法,您知道您获得的是 relative 导入,而不是 absolute 导入。 '..' 的意思是,转到我上面的目录:
from ..Common import Common
需要注意的是,这仅在您从包的外部将python作为模块运行时才有效。例如:
python -m Proj
原始的hacky方式
This method is still commonly used in some situations, where you aren't actually ever 'installing' your package. For example, it's popular with Django users.
您可以将 Common/添加到您的 sys.path(python 用来导入内容的路径列表):
import sys, os
sys.path.append(os.path.join(os.path.dirname(__file__), '..', 'Common'))
import Common
os.path.dirname(__file__)
只是给你当前python文件所在的目录,然后我们导航到'Common/'目录并导入'Common'模块。
关于python - 从 Python 中的相对路径导入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7505988/