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

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


当前回答

对我有用的是:

python -m pip install -user {package name}

该命令不需要sudo。这是在OSX Mojave上测试的。

其他回答

如果您正在使用虚拟环境,请使用pipenv install <模块名>而不是pip install <模块名>

为我工作。

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

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

今天,我发现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',
    ],

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

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

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

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