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

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


当前回答

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

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

其他回答

I know, that this is very old post but I didn't find any answer that was useful in my case (I am using arch linux). I had a similar problem installing "nest_asyncio" package which was definitely installed (visible when listing all the installed packages). There is a right way for arch linux users of installing python packages (as it was already explained here by Emanuel Fontelles). In my case the solution was just to uninstall the remaining not-working package (in my case "nest_asyncio") and then installing it again using the following command:

sudo pacman - s python-"nest_asyncio .

这解决了所有的问题。

我通过一种组合方法纠正了这个问题。首先,我听从克里斯的建议,打开命令行,输入“pip show packagename” 这提供了已安装包的位置。

接下来,我打开python,输入“import sys”,然后输入“sys”。path'来显示我的python在哪里搜索我导入的任何包。唉,第一步中显示的位置不在列表中。

最后一步,我输入“sys.path.append('package_location_seen_in_step_1')”。您可以选择重复步骤2,以查看位置现在在列表中。

测试步骤,尝试再次导入包…它的工作原理。

缺点呢?它是临时的,每次都需要将其添加到列表中。

我已经解决了我的问题,相同的库在一个项目(A)中工作良好,但在另一个项目(B)中导入这些相同的库会导致错误。我使用Pycharm作为IDE在Windows操作系统。 所以,在尝试了许多潜在的解决方案,但都未能解决问题后,我做了以下两件事(删除“Venv”文件夹,并重新配置解释器):

在项目(B)中,有一个名为(“venv”)的文件夹,位于外部库/。我删除了那个文件夹。

2-Step 1 (deleting "venv" folder) causes error in Python Interpreter Configuration, and there is a message shown at top of screen saying "Invalid python interpreter selected for the project" and "configure python interpreter", select that link and it opens a new window. There in "Project Interpreter" drop-down list, there is a Red colored line showing previous invalid interpreter. Now, Open this list and select the Python Interpreter(in my case, it is Python 3.7). Press "Apply" and "OK" at the bottom and you are good to go.

注意:这可能是我的项目(B)的虚拟环境无法识别已经安装和工作的库的问题。

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

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

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

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

如果上面提到的其他答案对您不起作用,请尝试删除pip缓存并重新安装包。我的机器运行的是Ubuntu14.04,它位于~/.cache/pip下。删除这个文件夹对我有用。