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

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


当前回答

在我的情况下,这是模块中缺少init.py文件的问题,我想在Python 2.7环境中导入该文件。

Python 3.3+具有隐式命名空间包,允许它在没有init.py文件的情况下创建包。

其他回答

Python导入机制确实有效,所以:

你的PYTHONPATH是错误的, 您的库没有安装在您认为的位置 您有另一个具有相同名称的库来掩盖这个库

今天,我发现setup.py包也会产生这个问题。

我有一个分类器< 3的设置

setup(
    name='data_reader',
    version='0.1',

    description='data_reader by Mithril ',
    long_description=long_description,

    author='Mithril',

    classifiers=[
        'Development Status :: 1 - Beta',
        'Programming Language :: Python :: 2',
        'Programming Language :: Python :: 2.6',
        'Programming Language :: Python :: 2.7',

        'Intended Audience :: Developers',
        'Operating System :: OS Independent',

        "License :: GPLv3",

        'Topic :: Internet :: WWW/HTTP',
        'Topic :: Software Development :: Libraries :: Tools',
        'Topic :: Software Development :: Libraries :: Python Modules',
    ],


)

我在conda env中使用python 3.7,我发现

pip install .
# or
pip install git+https://github.com/eromoe/data_reader

全部成功,但导入data_reader raise未找到。

经过一些测试,挖掘后只改变分类器

    classifiers=[
        'Development Status :: 1 - Beta',
        "Programming Language :: Python :: 3",
        'Intended Audience :: Developers',
        'Operating System :: OS Independent',
        "License :: GPLv3",
        'Topic :: Internet :: WWW/HTTP',
        'Topic :: Software Development :: Libraries :: Tools',
        'Topic :: Software Development :: Libraries :: Python Modules',
    ],

重新安装,导入恢复正常!

我无法让PYTHONPATH正常工作。我意识到添加export修复了这个问题:

(工作)

export PYTHONPATH=$PYTHONPATH:~/test/site-packages

vs.

(没有工作)

PYTHONPATH=$PYTHONPATH:~/test/site-packages

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

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

unalias python3

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

当您通过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.