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

其他回答

我在系统上安装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。(并仔细阅读错误消息)。

我也遇到过同样的问题,但上面的答案都没用。我快被逼疯了,直到我注意到那个系统。当我从父项目导入后,路径就不同了。原来我用importlib写了一个小函数来导入一个不在项目层次结构中的文件。坏主意:我忘了我做过这件事。更糟糕的是,导入过程搅乱了系统。路径,然后就这样走了。非常糟糕的主意。

解决方案是停止这种情况,并简单地将我需要导入的文件导入到项目中。另一种方法是将文件放到它自己的项目中,因为它需要不时地重新构建,并且重新构建可能与主项目的重新构建不一致。

检查您在IDE或代码编辑器的解释器和系统上使用的python版本是否相同。 例如,在终端中使用python3——version检查python版本 并在VSCode中通过cmd+shift+p->检查解释器的python版本:Select interpreter ->选择与您在终端中看到的相同的版本。

在我的例子中,我假设安装了一个包,因为它出现在pip freeze的输出中。但是,只是site-packages/*。Dist-info文件夹足以让PIP将其列为已安装,尽管缺少实际的包内容(可能是由于意外删除)。即使所有的路径设置都是正确的,也会发生这种情况,如果您尝试pip install <pkg>,它会说“需求已经满足”。

解决方案是手动删除dist-info文件夹,以便pip意识到包内容丢失。然后,重新安装应该会重新填充意外删除的任何内容

对我来说最简单的解决方案,但我在这篇文章中没有提到:

我安装了多个版本的Python,但试图使用Python3.7 -所以我必须使用:

Sudo pip3.7 install <package> . sh