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中找到该文件。什么好主意吗?会是权限问题吗?我需要一些执行许可吗?


当前回答

如果你时间紧迫,其他方法都失败了:

import sys
import os
wd = '/path/to/current/script/'
sys.path.append(wd)
os.chdir(wd)
print(os.getcwd())
print(sys.path)

其他回答

我解决了我自己的问题,我将写一篇总结错误的事情和解决方案:

该文件需要被确切地称为__init__.py。如果扩展名不同,例如在我的例子中是.py.bin,那么Python无法通过目录移动,然后就无法找到模块。要编辑这些文件,您需要使用Linux编辑器,例如vi或nano。如果你使用Windows编辑器,它会写一些隐藏字符。

另一个影响它的问题是,我用root安装了另一个Python版本,所以如果有人使用本地安装的Python,请确保运行程序的Python安装是本地Python。要检查这一点,只需执行哪个python,并查看可执行文件是否在您的本地目录中。如果不是,请更改路径,但要确保本地Python目录比其他Python目录更早。

根据你对orip帖子的评论,我猜事情是这样的:

You edited __init__.py on windows. The windows editor added something non-printing, perhaps a carriage-return (end-of-line in Windows is CR/LF; in unix it is LF only), or perhaps a CTRL-Z (windows end-of-file). You used WinSCP to copy the file to your unix box. WinSCP thought: "This has something that's not basic text; I'll put a .bin extension to indicate binary data." The missing __init__.py (now called __init__.py.bin) means python doesn't understand toolkit as a package. You create __init__.py in the appropriate directory and everything works... ?

Linux:导入的模块位于/usr/local/lib/python2.7/dist-packages中

如果你使用的是C语言编译的模块,不要忘记在sudo setup.py install后chmod .so文件。

sudo chmod 755 /usr/local/lib/python2.7/dist-packages/*.so

如果你时间紧迫,其他方法都失败了:

import sys
import os
wd = '/path/to/current/script/'
sys.path.append(wd)
os.chdir(wd)
print(os.getcwd())
print(sys.path)

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