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


当前回答

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

其他回答

我有同样的问题(Python 2.7 Linux),我已经找到了解决方案,我想分享它。在我的情况下,我有下面的结构:

Booklet
-> __init__.py
-> Booklet.py
-> Question.py
default
-> __init_.py
-> main.py

在'main.py'中,我尝试了以下所有的组合,但都失败了:

from Booklet import Question
from Question import Question
from Booklet.Question import Question
from Booklet.Question import *
import Booklet.Question
# and many othet various combinations ...

解决办法比我想象的要简单得多。我把文件夹“小册子”重命名为“小册子”,就是这样。现在Python可以通过在'main.py'中使用代码来正常导入类Question:

from booklet.Booklet import Booklet
from booklet.Question import Question
from booklet.Question import AnotherClass

由此我可以得出结论,像“小册子”这样的包名(文件夹)必须以小写开头,否则Python会将其与类名和文件名混淆。

显然,这不是你的问题,但John Fouhy的回答非常好,这个帖子几乎有任何可能导致这个问题的东西。所以,这是另一件事,我希望这能帮助到其他人。

在我的例子中,我使用sys.path.insert()导入一个本地模块,并从其他库中找不到模块。我不得不把sys.path.insert()放在报告模块未找到的导入下面。我认为最好的做法是将sys.path.insert()放在导入的底部。

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

from site-packages.toolkit.interface import interface

希望对你也有用!

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

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

您必须将文件__ init__.py放在您要导入的文件所在的同一目录中。 不能尝试从PYTHONPATH上配置的两个文件夹中导入同名的文件。

例如: /etc/environment

PYTHONPATH = PYTHONPATH:美元/ opt / folder1: / opt / folder2

/opt/folder1/foo

/opt/folder2/foo

而且,如果你试图导入foo文件,python将不知道你想要哪个。

从foo import…>>> importerror:没有foo模块