且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

成功安装pip后出现ImportError

更新时间:2023-02-25 19:53:17

TL; DR :通常存在多个版本的python解释器和pip版本.使用python -m pip install <library-name>代替pip install <library-name>将确保将该库安装到默认的python解释器中.

TL;DR: There are often multiple versions of python interpreters and pip versions present. Using python -m pip install <library-name> instead of pip install <library-name> will ensure that the library gets installed into the default python interpreter.

请注意:从我的个人经验来看,我建议不要使用sudo pip install将软件包安装到系统的默认python解释器中.这可能会导致各种混乱的问题. 每当您想通过sudo调用pip时,请先检查 virtualenv 是否不是更好的选择为你.

Please also note: From my personal experience I would advice against using sudo pip install to install packages into system's default python interpreter. This can lead to a various messy issues. Whenever you are tempted to call pip with sudo, please check first if a virtualenv is not a better option for you.

大多数现代系统都附带多个python解释器.每个解释器维护自己的一组已安装软件包.在安装新软件包时,重要的是要了解这些软件包实际安装在哪个解释器中.

Most modern systems ship multiple python interpreters. Each interpreter maintains its own set of installed packages. When installing new packages, it is important to understand into which interpreter those packages are actually installed.

在UNIX系统上,可以使用Shell来了解正在发生的事情.

On unix systems the shell can be used to understand what exactly is happening.

键入which -a python会显示PATH中的所有解释程序.第一行对应于从命令行运行python时使用的解释器.

Typing which -a python shows all interpreters that in your PATH. The first line corresponds to the interpreter that is used when you run python from the command line.

/private/tmp/py32/bin/python
/usr/local/bin/python
/usr/bin/python

每个pip版本完全属于一个解释器. which -a pip显示所有pip版本.同样,第一行是在外壳程序中键入pip时所要调用的内容.

Each pip version belongs to exactly one interpreter. which -a pip shows all pip versions. Again the first line is what will be called when you type pip in your shell.

/usr/local/bin/pip
/usr/bin/python

请注意,在这种情况下,python属于/private/tmp/py32/中安装的解释器,但是pip安装在解释器/usr/local/bin中.成功安装库后,您将无法在默认的python解释器中将其导入.

Note that in this case python belongs to the interpreter installed in /private/tmp/py32/, but pip installs into the interpreter /usr/local/bin. After a successful install of a library, you will not be able to import it in your default python interpreter.

那么如何导入已安装的库?

So how do you import the installed library?

您的第一个选择是使用完整的路径启动所需的解释器.因此,如果键入/usr/local/bin/python,则可以导入库.

Your first option is to start the desired interpreter with its full path. So if you type /usr/local/bin/python, you will be able to import the library.

第二个(通常是首选)选项是专门调用正确版本的pip.为此,可以使用python -m pip install <library-name>代替pip install <library-name>.这将调用属于您的默认python解释器的pip版本.

The second - often preferred - option is to specifically invoke the right version of pip. To do so, you can use python -m pip install <library-name> instead of pip install <library-name>. This will call the pip version that belongs to your default python interpreter.