在安装mechanize后,我似乎无法导入它。

我已经尝试从pip、easy_install和通过python setup.py从这个repo安装:https://github.com/abielr/mechanize。所有这些都无济于事,因为每次我输入Python交互时,我得到:

Python 2.7.3 (default, Aug  1 2012, 05:14:39) 
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import mechanize
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named mechanize
>>> 

我之前运行的安装报告已经成功完成,因此我希望导入能够正常工作。是什么导致了这个错误?


当前回答

当您通过easy_install或pip安装时,它是否成功完成?全输出是多少?您正在使用哪个python安装?如果您正在将模块安装到系统目录(如果您正在使用系统python安装),则可能需要在使用安装命令之前使用sudo。你的问题中没有太多有用的信息,但是一些工具可能会有帮助,包括:

echo $PYTHONPATH and/or echo $PATH: when importing modules, Python searches one of these environment variables (lists of directories, : delimited) for the module you want. Importing problems are often due to the right directory being absent from these lists which python, which pip, or which easy_install: these will tell you the location of each executable. It may help to know. Use virtualenv, like @JesseBriggs suggests. It works very well with pip to help you isolate and manage the modules and environment for separate Python projects.

其他回答

在我的情况下,我还必须为超级用户安装模块。

sudo su
pip install <module>

显然,superuse在某些情况下不能访问普通用户的文件。

这工作! !

这通常发生在模块安装到旧版本的python或其他目录时,不用担心,因为解决方案很简单。 - import module from模块所在目录。 你可以先导入python sys模块,然后从模块安装的路径导入

import sys
sys.path.append("directory in which module is installed")

import <module_name>

在重新定位的虚拟环境(venv)中也会出现此问题。

我有一个项目,在根目录中设置了venv。后来我创建了一个新用户,并决定将项目移动到这个用户。我没有只移动源文件并重新安装依赖项,而是将整个项目连同venv文件夹一起移动到新用户。

在此之后,我安装的依赖项被添加到全局site-packages文件夹中,而不是venv中的文件夹中,因此在这个env中运行的代码无法访问这些依赖项。

要解决这个问题,只需删除venv文件夹并重新创建它,如下所示:

$ deactivate
$ rm -rf venv
$ python3 -m venv venv
$ source venv/bin/activate
$ pip install -r requirements.txt

我在系统上安装2.7和3.5时遇到了这个问题,试图用Python-Telegram-Bot测试电报机器人。

在使用pip和pip3安装后,无论是否使用sudo,我都无法让它工作。我总是得到:

Traceback (most recent call last):
  File "telegram.py", line 2, in <module>
    from telegram.ext import Updater
  File "$USER/telegram.py", line 2, in <module>
    from telegram.ext import Updater
ImportError: No module named 'telegram.ext'; 'telegram' is not a package

正确地读取错误消息告诉我,python正在当前目录中查找telegram.py。我有一个脚本叫telegram。py当我调用import时,它被python加载了。

总结,确保在尝试导入时,当前工作目录中没有任何package.py。(并仔细阅读错误消息)。

我有类似的问题(在Windows上),根本原因在我的情况下是杀毒软件!它有“自动遏制”功能,用某种虚拟机包装正在运行的进程。 症状是:pip安装someemodule在一个cmd行窗口中正常工作,从另一个进程执行时导入someemodule失败,并出现错误

ModuleNotFoundError: No module named 'somemodule'