Python安装在本地目录。

我的目录树是这样的:

(local directory)/site-packages/toolkit/interface.py

我的代码在这里:

(local directory)/site-packages/toolkit/examples/mountain.py

为了运行这个例子,我编写了python mountain.py,在代码中我有:

from toolkit.interface import interface

我得到了一个错误:

Traceback (most recent call last):
  File "mountain.py", line 28, in ?
    from toolkit.interface import interface
ImportError: No module named toolkit.interface

我已经检查过系统了。这里有目录/site-packages。此外,我在工具包文件夹中有__init__.py.bin文件,以向Python表明这是一个包。我在examples目录中也有一个__init__.py.bin。

我不知道为什么Python无法在sys.path中找到该文件。什么好主意吗?会是权限问题吗?我需要一些执行许可吗?


当前回答

我也遇到了同样的问题:导入错误。此外,库已经100%正确安装。问题的根源是在我的PC上安装了3版的python (anaconda包)。这就是为什么图书馆没有安装在正确的地方。之后,我只是在我的IDE PyCharm中更改了适当的python版本。

其他回答

通过编写print (sys.path)修复了我的问题,并发现尽管清洁安装,python仍在使用过时的包。删除这些会使python自动使用正确的包。

我也犯了同样的错误。这是由于有人在与我的脚本相同的文件夹中创建了一个文件夹,该文件夹的名称与我从其他地方导入的模块冲突。它没有导入外部模块,而是在这个显然不包含预期模块的文件夹中查找。

另一个原因导致了这个问题

file.py

#!/bin/python
from bs4 import BeautifulSoup

如果你的默认python是pyyhon2

$ file $(which python)
/sbin/python: symbolic link to python2

File.py在这种情况下需要python3 (bs4) 你不能像这样用python2执行这个模块:

$ python file.py
# or
$ file.py
# or
$ file.py # if locate in $PATH

两种方法来修复这个错误,

# should be to make python3 as default by symlink
$ rm $(which python) && ln -s $(which python3) /usr/bin/python
# or use alias
alias python='/usr/bin.../python3'

或者将file.py中的shebang修改为

#!/usr/bin/...python3

要将一个目录标记为包,你需要一个名为__init__.py的文件,这有帮助吗?

使用sys.path.append对我有用,就像在回答中提到的那样。起初,我认为它不能工作,直到我意识到在目录路径之前有一个空格。所以要确保路径前没有错别字或空格