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中找到该文件。什么好主意吗?会是权限问题吗?我需要一些执行许可吗?
另一个原因导致了这个问题
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是在正确的地方,你已经安装了所有的依赖项,你仍然得到ImportError。
我也遇到了类似的问题,除了我的程序在使用PyCharm运行时运行良好,但当我从终端运行时出现上述错误。在深入研究之后,我发现PYTHONPATH没有项目目录的条目。所以,我设置PYTHONPATH每个Import语句在PyCharm上工作,但不是从终端:
export PYTHONPATH=$PYTHONPATH:`pwd` (OR your project root directory)
还有另一种方法可以使用sys。路径为:
import sys
sys.path.insert(0,'<project directory>') OR
sys.path.append('<project directory>')
您可以根据希望搜索项目的顺序使用插入/追加。