在安装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
>>> 

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


当前回答

在我的情况下(WIN10主机上的Ubuntu 20.04虚拟机),我有一个混乱的情况,安装了许多版本的Python和不同点的共享库(在文件系统的许多点安装pip)。我指的是3.8.10 Python版本。 经过多次测试,我用谷歌搜索发现了一个建议(但是“对不起,我没有链接”)。下面是我为解决这个问题所做的:

From shell session on Ubuntu 20.04 VM, (inside the Home, in my case /home/hduser), I've started a Jupyter Notebook session with the command "jupyter notebook". Then, when jupyter was running I've opened a .ipynb file to give commands. First : pip list --> give me the list of packages installed, and, sympy wasn't present (although I had installed it with "sudo pip install sympy" command. Last with the command !pip3 install sympy (inside jupyter notebook session) I've solved the problem, here the screen-shot : Now, with !pip list the package "sympy" is present, and working :

其他回答

在PyCharm中,我通过更改项目解释器路径解决了这个问题。

文件->设置->项目->项目解释器

File -> Invalidate缓存…之后可能需要。

在重新定位的虚拟环境(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

我也遇到了同样的问题,更新setuptools有帮助:

python3 -m pip install --upgrade pip setuptools wheel

之后,重新安装包,它应该可以正常工作:)

问题是,如果setuptools是旧的,那么包就会不正确地构建。

不确定这是否会帮助任何人,但我有一个类似的问题在Mac M1与zsh。原来我在我的.zshrc文件中设置了一个别名命令,与我的python命令(python3)同名。

为了解决这个问题,我只需要取消命令的别名。我跑:

unalias python3

从我的家庭终端和Visual Studio的终端。

我有同样的问题:脚本导入colorama是抛出和ImportError,但sudo pip安装colorama告诉我“包已经安装”。

我的解决方案:运行pip没有sudo: pip安装colorama。然后pip同意需要安装它,安装了它,我的脚本运行了。

我的环境是Ubuntu 14.04 32位;我想我在激活virtualenv之前和之后都看到了这个。

更新:更好的方法是使用python -m pip install <package>。这样做的好处是,由于您正在执行想要在其中安装包的特定python版本,pip将明确地将包安装到“正确”的python中。再次强调,在这种情况下不要使用sudo。然后在正确的位置获得包,但可能具有(不需要的)根权限。