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


当前回答

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

其他回答

我的观点是:

随地吐痰:

Traceback (most recent call last):
      File "bash\bash.py", line 454, in main
        import bosh
      File "Wrye Bash Launcher.pyw", line 63, in load_module
        mod = imp.load_source(fullname,filename+ext,fp)
      File "bash\bosh.py", line 69, in <module>
        from game.oblivion.RecordGroups import MobWorlds, MobDials, MobICells, \
    ImportError: No module named RecordGroups

This confused the hell out of me - went through posts and posts suggesting ugly syspath hacks (as you see my __init__.py were all there). Well turns out that game/oblivion.py and game/oblivion was confusing python which spit out the rather unhelpful "No module named RecordGroups". I'd be interested in a workaround and/or links documenting this (same name) behavior -> EDIT (2017.01.24) - have a look at What If I Have a Module and a Package With The Same Name? Interestingly normally packages take precedence but apparently our launcher violates this.

编辑(2015.01.17):我没有提到我们使用一个自定义启动器解剖这里。

Does

(local directory)/site-packages/toolkit

有__init__.py?

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

在我的例子中,因为我使用PyCharm和PyCharm为项目文件夹中的每个项目创建了一个“venv”,但它只是python的一个迷你env。虽然您已经在Python中安装了所需的库,但在您的自定义项目“venv”中,它不可用。这是PyCharm中出现'ImportError: No module named xxxxxx'的真正原因。 要解决此问题,您必须按以下步骤向项目自定义env添加库:

在PyCharm中,从菜单“文件”->设置 在“设置”对话框中,输入“项目:XXXProject->项目解释器” 点击“添加”按钮,会弹出“Available Packages”对话框 搜索你的库,点击“安装包” 然后,所有你需要的包将安装在你的项目自定义的“venv”文件夹。

享受。

对我来说,这是件非常愚蠢的事。我使用pip3 install安装了这个库,但是我运行的程序是python program.py,而不是python3 program.py。

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

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

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