简体   繁体   English

使用多个 Python 和 IPython 路径运行 Jupyter

[英]Running Jupyter with multiple Python and IPython paths

I'd like to work with Jupyter notebooks, but have had difficulty doing basic imports (such as import matplotlib).我想使用 Jupyter 笔记本,但在进行基本导入(例如导入 matplotlib)时遇到了困难。 I think this was because I have several user-managed python installations.我认为这是因为我有几个用户管理的 python 安装。 For instance:例如:

> which -a python
/usr/bin/python
/usr/local/bin/python

> which -a ipython
/Library/Frameworks/Python.framework/Versions/3.5/bin/ipython
/usr/local/bin/ipython

> which -a jupyter
/Library/Frameworks/Python.framework/Versions/3.5/bin/jupyter
/usr/local/bin/jupyter

I used to have anaconda, but removed if from the ~/anaconda directory.我曾经有 anaconda,但如果从 ~/anaconda 目录中删除。 Now, when I start a Jupyter Notebook, I get a Kernel Error:现在,当我启动 Jupyter Notebook 时,我收到 Kernel 错误:

File "/Library/Frameworks/Python.framework/Versions/3.5/lib/pytho‌n3.5/subprocess.py",
line 947, in init restore_signals, start_new_session)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/pytho‌n3.5/subprocess.py",
line 1551, in _execute_child raise child_exception_type(errno_num, err_msg)
FileNotFoundError: [Errno 2]
No such file or directory: '/Users/npr1/anaconda/envs/py27/bin/python' 

What should I do?!我应该怎么办?!

This is fairly straightforward to fix, but it involves understanding three different concepts:这很容易解决,但它涉及理解三个不同的概念:

  1. How Unix/Linux/OSX use $PATH to find executables ( %PATH% in Windows) Unix/Linux/OSX 如何使用$PATH查找可执行文件(Windows 中的%PATH%
  2. How Python installs and finds packages Python 如何安装和查找包
  3. How Jupyter knows what Python to use Jupyter 如何知道要使用什么 Python

For the sake of completeness, I'll try to do a quick ELI5 on each of these, so you'll know how to solve this issue in the best way for you.为完整起见,我将尝试对其中的每一个进行快速 ELI5,以便您知道如何以最适合您的方式解决此问题。

1. Unix/Linux/OSX $PATH 1. Unix/Linux/OSX $PATH

When you type any command at the prompt (say, python ), the system has a well-defined sequence of places that it looks for the executable.当您在提示符下键入任何命令(例如, python )时,系统具有一个明确定义的位置序列,用于查找可执行文件。 This sequence is defined in a system variable called PATH , which the user can specify.此序列在名为PATH的系统变量中定义,用户可以指定该变量。 To see your PATH , you can type echo $PATH .要查看您的PATH ,您可以输入echo $PATH

The result is a list of directories on your computer, which will be searched in order for the desired executable.结果是您计算机上的目录列表,将按顺序搜索所需的可执行文件。 From your output above, I assume that it contains this:从上面的输出中,我假设它包含以下内容:

$ echo $PATH
/usr/bin/:/Library/Frameworks/Python.framework/Versions/3.5/bin/:/usr/local/bin/

In windows echo %path%在 Windows 中echo %path%

Probably with some other paths interspersed as well.可能还穿插了一些其他路径。 What this means is that when you type python , the system will go to /usr/bin/python .这意味着当您键入python ,系统将转到/usr/bin/python When you type ipython , in this example, the system will go to /Library/Frameworks/Python.framework/Versions/3.5/bin/ipython , because there is no ipython in /usr/bin/ .当您输入ipython ,在本例中,系统将转到/Library/Frameworks/Python.framework/Versions/3.5/bin/ipython ,因为/usr/bin/没有ipython

It's always important to know what executable you're using, particularly when you have so many installations of the same program on your system.了解您正在使用的可执行文件总是很重要的,尤其是当您的系统上安装了如此多的相同程序时。 Changing the path is not too complicated;改变路径并不太复杂; see eg How to permanently set $PATH on Linux?参见例如如何在 Linux 上永久设置 $PATH? . .

Windows - How to set environment variables in Windows 10 Windows - 如何在 Windows 10 中设置环境变量

2. How Python finds packages 2. Python 如何查找包

When you run python and do something like import matplotlib , Python has to play a similar game to find the package you have in mind.当您运行 python 并执行诸如import matplotlib ,Python 必须玩类似的游戏才能找到您想要的包。 Similar to $PATH in unix, Python has sys.path that specifies these:类似于 unix 中的$PATH ,Python 有sys.path指定这些:

$ python
>>> import sys
>>> sys.path
['',
 '/Users/jakevdp/anaconda/lib/python3.5', 
 '/Users/jakevdp/anaconda/lib/python3.5/site-packages',
 ...]

Some important things: by default, the first entry in sys.path is the current directory.一些重要的事情:默认情况下, sys.path的第一个条目是当前目录。 Also, unless you modify this (which you shouldn't do unless you know exactly what you're doing) you'll usually find something called site-packages in the path: this is the default place that Python puts packages when you install them using python setup.py install , or pip , or conda , or a similar means.此外,除非你修改它(除非你确切地知道你在做什么,否则你不应该这样做)你通常会在路径中找到一个叫做site-packages东西:这是安装包时 Python 放置包的默认位置使用python setup.py install ,或pip ,或conda ,或类似的方法。

The important thing to note is that each python installation has its own site-packages , where packages are installed for that specific Python version .需要注意的重要一点是,每个 python 安装都有自己的 site-packages ,其中安装了针对特定 Python 版本的包 In other words, if you install something for, eg /usr/bin/python , then ~/anaconda/bin/python can't use that package , because it was installed on a different Python!换句话说,如果你安装了一些东西,例如/usr/bin/python ,那么~/anaconda/bin/python不能使用那个包,因为它安装在不同的 Python 上! This is why in our twitter exchange I recommended you focus on one Python installation, and fix your $PATH so that you're only using the one you want to use.这就是为什么在我们的 twitter 交流中我建议你专注于一个 Python 安装,并修复你的$PATH以便你只使用你想使用的那个。

There's another component to this: some Python packages come bundled with stand-alone scripts that you can run from the command line (examples are pip , ipython , jupyter , pep8 , etc.) By default, these executables will be put in the same directory path as the Python used to install them, and are designed to work only with that Python installation .这还有另一个组件:一些 Python 包与您可以从命令行运行的独立脚本捆绑在一起(例如pipipythonjupyterpep8等)默认情况下,这些可执行文件将放在同一目录中路径作为用于安装它们的 Python,并且旨在仅与该 Python 安装一起使用

That means that, as your system is set-up, when you run python , you get /usr/bin/python , but when you run ipython , you get /Library/Frameworks/Python.framework/Versions/3.5/bin/ipython which is associated with the Python version at /Library/Frameworks/Python.framework/Versions/3.5/bin/python !这意味着,当你的系统设置好时,当你运行python ,你会得到/usr/bin/python ,但是当你运行ipython ,你会得到/Library/Frameworks/Python.framework/Versions/3.5/bin/ipython它与/Library/Frameworks/Python.framework/Versions/3.5/bin/python的 Python 版本相关联! Further, this means that the packages you can import when running python are entirely separate from the packages you can import when running ipython or a Jupyter notebook: you're using two completely independent Python installations.此外,这意味着您在运行python时可以导入的包与运行ipython或 Jupyter notebook 时可以导入的包完全分开:您正在使用两个完全独立的 Python 安装。

So how to fix this?那么如何解决这个问题呢? Well, first make sure your $PATH variable is doing what you want it to.好吧,首先确保您的$PATH变量正在执行您想要的操作。 You likely have a startup script called something like ~/.bash_profile or ~/.bashrc that sets this $PATH variable.您可能有一个名为~/.bash_profile~/.bashrc类的启动脚本,用于设置此$PATH变量。 On Windows, you can modify the user specific environment variables.在 Windows 上,您可以修改用户特定的环境变量。 You can manually modify that if you want your system to search things in a different order.如果您希望系统以不同的顺序搜索内容,您可以手动修改它。 When you first install anaconda/miniconda, there will be an option to do this automatically (add Python to the PATH): say yes to that, and then python will always point to ~/anaconda/python , which is probably what you want.当您第一次安装 anaconda/miniconda 时,将有一个选项可以自动执行此操作(将 Python 添加到 PATH):对此说是,然后python将始终指向~/anaconda/python ,这可能是您想要的。

3. How Jupyter knows what Python to use 3. Jupyter 如何知道使用什么 Python

We're not totally out of the water yet.我们还没有完全脱离水面。 You mentioned that in the Jupyter notebook, you're getting a kernel error: this indicates that Jupyter is looking for a non-existent Python version.您提到在 Jupyter 笔记本中,您收到内核错误:这表明 Jupyter 正在寻找不存在的 Python 版本。

Jupyter is set-up to be able to use a wide range of "kernels", or execution engines for the code. Jupyter 被设置为能够使用广泛的“内核”或代码执行引擎。 These can be Python 2, Python 3, R, Julia, Ruby... there are dozens of possible kernels to use.这些可以是 Python 2、Python 3、R、Julia、Ruby……有许多可能的内核可供使用。 But in order for this to happen, Jupyter needs to know where to look for the associated executable: that is, it needs to know which path the python sits in.但是为了实现这一点,Jupyter 需要知道在哪里寻找相关的可执行文件:也就是说,它需要知道python所在的路径。

These paths are specified in jupyter's kernelspec , and it's possible for the user to adjust them to their desires.这些路径在 jupyter 的kernelspec中指定,用户可以根据自己的需要调整它们。 For example, here's the list of kernels that I have on my system:例如,这是我系统上的内核列表:

$ jupyter kernelspec list
Available kernels:
  python2.7        /Users/jakevdp/.ipython/kernels/python2.7
  python3.3        /Users/jakevdp/.ipython/kernels/python3.3
  python3.4        /Users/jakevdp/.ipython/kernels/python3.4
  python3.5        /Users/jakevdp/.ipython/kernels/python3.5
  python2          /Users/jakevdp/Library/Jupyter/kernels/python2
  python3          /Users/jakevdp/Library/Jupyter/kernels/python3

Each of these is a directory containing some metadata that specifies the kernel name, the path to the executable, and other relevant info.其中每一个都是一个包含一些元数据的目录,这些元数据指定了内核名称、可执行文件的路径和其他相关信息。
You can adjust kernels manually, editing the metadata inside the directories listed above.您可以手动调整内核,编辑上面列出的目录中的元数据。

The command to install a kernel can change depending on the kernel.安装内核的命令可能因内核而异。 IPython relies on the ipykernel package which contains a command to install a python kernel: for example IPython 依赖于ipykernel 包,其中包含安装 python 内核的命令:例如

$  python -m ipykernel install

It will create a kernelspec associated with the Python executable you use to run this command.它将创建一个与用于运行此命令的 Python 可执行文件相关联的 kernelspec。 You can then choose this kernel in the Jupyter notebook to run your code with that Python.然后,您可以在 Jupyter Notebook 中选择此内核以使用该 Python 运行您的代码。

You can see other options that ipykernel provides using the help command:您可以使用 help 命令查看 ipykernel 提供的其他选项:

$ python -m ipykernel install --help
usage: ipython-kernel-install [-h] [--user] [--name NAME]
                              [--display-name DISPLAY_NAME] [--prefix PREFIX]
                              [--sys-prefix]

Install the IPython kernel spec.

optional arguments:
  -h, --help            show this help message and exit
  --user                Install for the current user instead of system-wide
  --name NAME           Specify a name for the kernelspec. This is needed to
                        have multiple IPython kernels at the same time.
  --display-name DISPLAY_NAME
                        Specify the display name for the kernelspec. This is
                        helpful when you have multiple IPython kernels.
  --prefix PREFIX       Specify an install prefix for the kernelspec. This is
                        needed to install into a non-default location, such as
                        a conda/virtual-env.
  --sys-prefix          Install to Python's sys.prefix. Shorthand for
                        --prefix='/Users/bussonniermatthias/anaconda'. For use
                        in conda/virtual-envs.

Note: the recent version of anaconda ships with an extension for the notebook that should automatically detect your various conda environments if the ipykernel package is installed in it.注意:最新版本的anaconda附带了一个笔记本扩展,如果其中安装了ipykernel包,它应该会自动检测您的各种ipykernel环境。

Wrap-up: Fixing your Issue总结:解决您的问题

So with that background, your issue is quite easy to fix:因此,在这种背景下,您的问题很容易解决:

  1. Set your PATH so that the desired Python version is first.设置您的PATH以便所需的 Python 版本是第一个。 For example, you could run export PATH="/path/to/python/bin:$PATH" to specify (one time) which Python you'd like to use.例如,您可以运行export PATH="/path/to/python/bin:$PATH"来指定(一次)您想要使用的 Python。 To do this permanently, add that line to your .bash_profile / .bashrc (note that anaconda can do this automatically for you when you install it).要永久执行此操作,请将该行添加到您的.bash_profile / .bashrc (请注意,anaconda 可以在您安装时自动为您执行此操作)。 I'd recommend using the Python that comes with anaconda or miniconda: this will allow you to conda install all the tools you need.我建议使用 anaconda 或 miniconda 附带的 Python:这将允许您 conda conda install您需要的所有工具。

  2. Make sure the packages you want to use are installed for that python.确保为该python 安装了要使用的软件包。 If you're using conda, you can type, eg conda install jupyter matplotlib scikit-learn to install those packages for anaconda/bin/python .如果你使用 conda,你可以输入,例如conda install jupyter matplotlib scikit-learn来安装anaconda/bin/python那些包。

  3. Make sure that your Jupyter kernels point to the Python versions you want to use.确保您的 Jupyter 内核指向您要使用的 Python 版本。 When you conda install jupyter it should set this up for anaconda/bin/python automatically.当您conda install jupyter它应该自动为anaconda/bin/python进行设置。 Otherwise you can use the jupyter kernelspec command or python -m ipykernel install command to adjust existing kernels or install new ones.否则,您可以使用jupyter kernelspec命令或python -m ipykernel install命令来调整现有内核或安装新内核。

  4. For installing modules into other Python Jupyter kernels not managed by Anaconda, you need to copy the path to the Python executable for the kernel and run /path/to/python -m pip install <package>要将模块安装到其他不受 Anaconda 管理的 Python Jupyter 内核中,您需要复制内核的 Python 可执行文件的路径并运行/path/to/python -m pip install <package>

Hopefully that's clear... good luck!希望这很清楚……祝你好运!

@jakevdp explained it very well. @jakevdp解释得很好。

When I updated my ubuntu I also had the same problem and I solved it by changing the kernel configuration file(kernel.json).当我更新我的 ubuntu 时,我也遇到了同样的问题,我通过更改内核配置文件 (kernel.json) 解决了它。 To list the kernel files location.列出内核文件位置。 Use使用

jupyter kernelspec list

It will return它会回来

Available kernels:
  python3    /home/user1/.local/share/jupyter/kernels/python3
  python2    /usr/local/share/jupyter/kernels/python2

I was using python3 so I changed the file at我使用的是 python3,所以我更改了文件

/home/user1/.local/share/jupyter/kernels/python3

by following step通过以下步骤

nano /home/user1/.local/share/jupyter/kernels/python3/kernel.json

There inside argv I changed the first parameter(ie python3 directory path) formargv里面我改变了第一个参数(即 python3 目录路径)的形式

"/usr/bin/python3.5"

to

"/usr/bin/python3"

and saved it with ctr+x and restarted jupyter-notebook.并用ctr+x保存它并重新启动 jupyter-notebook。

also found not to put your virtual environment inside the git repo as it becomes non-readable to read the python packages.还发现不要将您的虚拟环境放在 git repo 中,因为读取 python 包变得不可读。 seems different permissions use while reading and writing (writing - installing a package - use pip), how unable to read.读写时使用的权限似乎不同(写入 - 安装包 - 使用 pip),如何无法读取。 Hence, for me the python libraries were getting read from system installation and not virtual environment.因此,对我来说,python 库是从系统安装而不是虚拟环境中读取的。

@jakevdp's Answer above & his blog https://jakevdp.github.io/blog/2017/12/05/installing-python-packages-from-jupyter/ gives fairly good idea about what's going wrong, however just updating path from shell was not working for me, there are 2 ways that worked for me @jakevdp 上面的回答和他的博客https://jakevdp.github.io/blog/2017/12/05/installing-python-packages-from-jupyter/给出了关于出了什么问题的好主意,但是只是从 shell 更新路径对我不起作用,有两种方法对我有用

Either update path on notebook using magic commands, run below on cell使用魔术命令更新笔记本上的路径,在单元格上运行

originalPath = %env PATH
%env PATH = [local anaconda path]/kernels/[custom_kernel]/bin/:$originalPath

Or you can even update the kernel.json & set the path in env或者你甚至可以更新 kernel.json 并在 env 中设置路径

{
    "argv": [
        "[custom kernel path]/bin/python",
        "-m",
        "ipykernel_launcher",
        "-f",
        "{connection_file}"
    ],
    "env": {
        "PATH": "[custom kernel path]/bin/:[rest of the paths]"
    },

    "display_name": "custom_kerbel",

    "language": "python"
}

If you just want to install a package into the current environment to be able to import it, you can use the %pip and %conda magicks.如果您只想将 package 安装到当前环境中以便能够导入它,您可以使用%pip%conda conda 魔法。

As you mention anaconda, you probably should use conda to install:正如您提到的 anaconda,您可能应该使用conda安装:

# Install a conda package in the current Jupyter kernel
%conda install <dependency_name>

Alternatively, if you need to use pip :或者,如果您需要使用pip

# Install a pip package in the current Jupyter kernel
%pip install <python_package_name>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM