从Python中的相对路径导入 [英] Importing from a relative path in Python
本文介绍了从Python中的相对路径导入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个用于客户端代码的文件夹,一个用于我的服务器代码的文件夹,以及一个用于在它们之间共享的代码的文件夹
I have a folder for my client code, a folder for my server code, and a folder for code that is shared between them
Proj/
Client/
Client.py
Server/
Server.py
Common/
__init__.py
Common.py
如何从Server.py和Client.py导入Common.py?
How do I import Common.py from Server.py and Client.py?
推荐答案
不要进行相对导入。
来自 PEP8 :
非常不鼓励进行包内进口的相对进口。
Relative imports for intra-package imports are highly discouraged.
将所有代码放入一个超级包(即myapp)并使用子包用于客户端,服务器和公共代码。
Put all your code into one super package (i.e. "myapp") and use subpackages for client, server and common code.
更新:
Python 2.6和3.x支持正确的相对导入(...)。有关详细信息,请参阅 Dave的答案。
Update: "Python 2.6 and 3.x supports proper relative imports (...)". See Dave's answers for more details.
这篇关于从Python中的相对路径导入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文