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


当前回答

是的。您需要该目录包含__init__.py文件,该文件是初始化包的文件。来,看看这个。

需要__init__.py文件才能使Python将目录视为包含包;这样做是为了防止具有通用名称的目录(如string)在无意中隐藏之后在模块搜索路径上出现的有效模块。在最简单的情况下,__init__.py可以只是一个空文件,但它也可以执行包的初始化代码或设置__all__变量,稍后将介绍。

其他回答

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

另一个原因导致了这个问题

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

我也有类似的问题。我创建了一个名为python3.6的新虚拟环境。

conda create -n python3.6 python=3.6
pip install pandas

一切正常,但当我运行脚本时,发生了一个错误

ModuleNotFoundError: No module named 'pandas'

我发现Python包的元数据和pip的缓存已经更新,但它实际上没有下载pandas包。 所以我试着让皮普重新安装

pip uninstall pandas --no-cache-dir
pip install pandas 

这就解决了问题。

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

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

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