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


当前回答

所有python文件的文件编码必须为utf-8。

请看这里:https://github.com/jupyter/notebook/issues/3166#issuecomment-581332097

其他回答

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

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

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

这招对我很管用: 在父文件夹内创建__init__.py文件(在您的情况下,在site-packages文件夹内)。并像这样导入:

from site-packages.toolkit.interface import interface

希望对你也有用!

根据你对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... ?

在我的例子中,我包含了打包路径。鸡蛋文件夹,而不是下面的实际包裹。我复制包到顶级,它工作。

Does

(local directory)/site-packages/toolkit

有__init__.py?

为了让导入遍历你的目录,每个目录必须有一个__init__.py文件。