当我想在特定文件夹中安装某个 Python 包(使用 pip install -t),然后从该包导入模块时,出现错误。
我在包的 Github 上发布了这个问题,结果发现我无法在某个文件夹中安装包;不支持以这种方式安装软件包。
Even without google collab, I can reproduce the import error when trying to install sklearn in some specific folder with pip install -t sklearnFolder then importing it as sklearnFolder.sklearn.manifold.
That is not a supported way of installing / using scikit-lean. One reason why it wouldn't work is that a few modules in scikit-learn use absolute imports (e.g. from sklearn import something) which will fail with such setup.
You should either install it with pip install or if you want to have it in some specific folder, clone the repo to that folder, then run pip install -e , in both cases it will be imported as sklearn.
来自https://github.com/scikit-learn/scikit-learn/issues/11656
我不太明白这个解释。
我想的是这样的
from folderName.package import module
与
相同from package import module
因为它们都是绝对进口的。如图所示,它们都完全指定了导入模块的路径。所以我的理解有一些问题,但我不知道它是什么。
最佳答案
在导入中,您不指定文件夹名称作为包的前缀。如果包已安装或位于 python 路径中,则只需使用包名称即可导入。
# Assume the below structure is under a directory (folder) called /app/home/packages.
reservation/ This is your top-level pacakge
__init__.py Initialize the package
hotels/ Subpackage for hotel reservations
__init__.py
slots.py
bid.py
demand.py
...
restaurents/ Another Subpackage under hotels
__init__.py
cuisine.py
hours.py
tableslots.py
...
rewards/ Subpackage for rewards
__init__.py
points.py
discounts.py
membersonly.py
...
由于该包位于/app/home/packages 下,因此当您为文件夹名称添加前缀时,以下导入无效。
from packages.reservation import hotels
正确的导入方法是从具有包初始化 __init__.py 的实际包中导入。如果您在示例中看到,预订文件夹有 __init__.py。
from reservation import hotels
如果要导入hotels下的子模块,则需要加上package前缀:
from reservation.hotels import restaurents
或者,您可以直接导入子模块,但在使用时必须添加包前缀:
import reservation.hotels.restaurents
关于python - 需要帮助理解有关 Python 中相对导入和绝对导入的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51510407/