标签归档:ipython

在IPython Notebook中同时使用Python 2.x和Python 3.x

问题:在IPython Notebook中同时使用Python 2.x和Python 3.x

我使用IPython笔记本,并且希望能够选择在IPython中创建2.x或3.x python笔记本。

我最初有Anaconda。使用Anaconda时,必须更改全局环境变量以选择所需的python版本,然后才能启动IPython。这不是我想要的,所以我卸载了Anaconda,现在使用MacPorts和PiP设置了自己的安装。看来我还是要用

port select --set python <python version> 

在python 2.x和3.x之间切换。这并不比anaconda解决方案好。

启动IPython笔记本后,是否有一种方法可以选择要使用的python版本,最好使用当前的MacPorts构建?

I use IPython notebooks and would like to be able to select to create a 2.x or 3.x python notebook in IPython.

I initially had Anaconda. With Anaconda a global environment variable had to be changed to select what version of python you want and then IPython could be started. This is not what I was looking for so I uninstalled Anaconda and now have set up my own installation using MacPorts and PiP. It seems that I still have to use

port select --set python <python version> 

to toggle between python 2.x and 3.x. which is no better than the anaconda solution.

Is there a way to select what version of python you want to use after you start an IPython notebook, preferably with my current MacPorts build?


回答 0

这里的想法是安装多个ipython内核。这是有关Python的说明。如果你不使用Python,我最近添加的说明采用纯virtualenvs。

水蟒> = 4.1.0

从版本4.1.0开始,anaconda包含一个特殊的程序包nb_conda_kernels,该程序包可检测笔记本内核的conda环境并自动注册它们。这使得使用新的python版本就像创建新的conda环境一样容易:

conda create -n py27 python=2.7 ipykernel
conda create -n py36 python=3.6 ipykernel

重新启动jupyter notebook之后,新内核可通过图形界面使用。请注意,必须将新软件包明确安装到新环境中。conda文档中的“ 管理环境”部分提供了更多信息。

手动注册内核

不想使用nb_conda_kernels或仍使用旧版本的anaconda的用户可以使用以下步骤来手动注册ipython内核。

配置python2.7环境:

conda create -n py27 python=2.7
conda activate py27
conda install notebook ipykernel
ipython kernel install --user

配置python3.6环境:

conda create -n py36 python=3.6
conda activate py36
conda install notebook ipykernel
ipython kernel install --user

在此之后,你应该能够之间进行选择python2
python3创造的接口一个新的笔记本时。

另外,如果要更改内核名称,可以将--name--display-name选项传递给ipython kernel install。请参阅ipython kernel install --help以获取更多信息。

The idea here is to install multiple ipython kernels. Here are instructions for anaconda. If you are not using anaconda, I recently added instructions using pure virtualenvs.

Anaconda >= 4.1.0

Since version 4.1.0, anaconda includes a special package nb_conda_kernels that detects conda environments with notebook kernels and automatically registers them. This makes using a new python version as easy as creating new conda environments:

conda create -n py27 python=2.7 ipykernel
conda create -n py36 python=3.6 ipykernel

After a restart of jupyter notebook, the new kernels are available over the graphical interface. Please note that new packages have to be explicitly installed into the new environments. The Managing environments section in conda’s docs provides further information.

Manually registering kernels

Users who do not want to use nb_conda_kernels or still use older versions of anaconda can use the following steps to manually register ipython kernels.

configure the python2.7 environment:

conda create -n py27 python=2.7
conda activate py27
conda install notebook ipykernel
ipython kernel install --user

configure the python3.6 environment:

conda create -n py36 python=3.6
conda activate py36
conda install notebook ipykernel
ipython kernel install --user

After that you should be able to choose between python2
and python3 when creating a new notebook in the interface.

Additionally you can pass the --name and --display-name options to ipython kernel install if you want to change the names of your kernels. See ipython kernel install --help for more informations.


回答 1

如果您在Python 3上运行Jupyter,则可以这样设置Python 2内核:

python2 -m pip install ipykernel

python2 -m ipykernel install --user

http://ipython.readthedocs.io/en/stable/install/kernel_install.html

If you’re running Jupyter on Python 3, you can set up a Python 2 kernel like this:

python2 -m pip install ipykernel

python2 -m ipykernel install --user

http://ipython.readthedocs.io/en/stable/install/kernel_install.html


回答 2

这些说明说明了如何为非anaconda用户在单独的虚拟环境中安装python2和python3内核。如果您使用anaconda,请找到我的其他答案,以直接针对anaconda量身定制解决方案。

我假设您已经jupyter notebook安装了。


首先,请确保您有python2和提供的python3口译员pip

在ubuntu上,您可以通过以下方式安装它们:

sudo apt-get install python-dev python3-dev python-pip python3-pip

接下来准备并注册内核环境

python -m pip install virtualenv --user

# configure python2 kernel
python -m virtualenv -p python2 ~/py2_kernel
source ~/py2_kernel/bin/activate
python -m pip install ipykernel
ipython kernel install --name py2 --user
deactivate

# configure python3 kernel
python -m virtualenv -p python3 ~/py3_kernel
source ~/py3_kernel/bin/activate
python -m pip install ipykernel
ipython kernel install --name py3 --user
deactivate

为了简化操作,您可能需要将激活命令的外壳别名添加到外壳配置文件中。根据不同的系统和外壳使用,这可以是例如~/.bashrc~/.bash_profile~/.zshrc

alias kernel2='source ~/py2_kernel/bin/activate'
alias kernel3='source ~/py3_kernel/bin/activate'

重新启动外壳程序后,现在可以在激活要使用的环境后安装新软件包。

kernel2
python -m pip install <pkg-name>
deactivate

要么

kernel3
python -m pip install <pkg-name>
deactivate

These instructions explain how to install a python2 and python3 kernel in separate virtual environments for non-anaconda users. If you are using anaconda, please find my other answer for a solution directly tailored to anaconda.

I assume that you already have jupyter notebook installed.


First make sure that you have a python2 and a python3 interpreter with pip available.

On ubuntu you would install these by:

sudo apt-get install python-dev python3-dev python-pip python3-pip

Next prepare and register the kernel environments

python -m pip install virtualenv --user

# configure python2 kernel
python -m virtualenv -p python2 ~/py2_kernel
source ~/py2_kernel/bin/activate
python -m pip install ipykernel
ipython kernel install --name py2 --user
deactivate

# configure python3 kernel
python -m virtualenv -p python3 ~/py3_kernel
source ~/py3_kernel/bin/activate
python -m pip install ipykernel
ipython kernel install --name py3 --user
deactivate

To make things easier, you may want to add shell aliases for the activation command to your shell config file. Depending on the system and shell you use, this can be e.g. ~/.bashrc, ~/.bash_profile or ~/.zshrc

alias kernel2='source ~/py2_kernel/bin/activate'
alias kernel3='source ~/py3_kernel/bin/activate'

After restarting your shell, you can now install new packages after activating the environment you want to use.

kernel2
python -m pip install <pkg-name>
deactivate

or

kernel3
python -m pip install <pkg-name>
deactivate

回答 3

使用当前版本的Notebook / Jupyter,您可以创建Python3内核。使用Python 2从命令行启动新的笔记本应用程序后,您应该在下拉菜单“新建”中看到条目“ Python 3”。这为您提供了一个使用Python 3的笔记本。因此,您可以并排放置两个笔记本,并使用不同的Python版本。

细节

  1. 创建此目录: mkdir -p ~/.ipython/kernels/python3
  2. ~/.ipython/kernels/python3/kernel.json使用以下内容创建此文件:

    {
        "display_name": "IPython (Python 3)", 
        "language": "python", 
        "argv": [
            "python3", 
            "-c", "from IPython.kernel.zmq.kernelapp import main; main()", 
            "-f", "{connection_file}"
        ], 
        "codemirror_mode": {
            "version": 2, 
            "name": "ipython"
        }
    }
  3. 重新启动笔记本服务器。

  4. 从下拉菜单“新建”中选择“ Python 3”
  5. 使用Python 3笔记本
  6. 从下拉菜单“新建”中选择“ Python 2”
  7. 使用Python 2笔记本

With a current version of the Notebook/Jupyter, you can create a Python3 kernel. After starting a new notebook application from the command line with Python 2 you should see an entry „Python 3“ in the dropdown menu „New“. This gives you a notebook that uses Python 3. So you can have two notebooks side-by-side with different Python versions.

The Details

  1. Create this directory: mkdir -p ~/.ipython/kernels/python3
  2. Create this file ~/.ipython/kernels/python3/kernel.json with this content:

    {
        "display_name": "IPython (Python 3)", 
        "language": "python", 
        "argv": [
            "python3", 
            "-c", "from IPython.kernel.zmq.kernelapp import main; main()", 
            "-f", "{connection_file}"
        ], 
        "codemirror_mode": {
            "version": 2, 
            "name": "ipython"
        }
    }
    
  3. Restart the notebook server.

  4. Select „Python 3“ from the dropdown menu „New“
  5. Work with a Python 3 Notebook
  6. Select „Python 2“ from the dropdown menu „New“
  7. Work with a Python 2 Notebook

回答 4

提供了一个解决方案,该解决方案允许我通过配置Ipython kernelspec来保留MacPorts的安装。

要求:

  • MacPorts安装在通常的/ opt目录中
  • python 2.7是通过macports安装的
  • python 3.4通过macports安装
  • 为python 2.7安装了ipython
  • 为python 3.4安装了ipython

对于python 2.x:

$ cd /opt/local/Library/Frameworks/Python.framework/Versions/2.7/bin
$ sudo ./ipython kernelspec install-self

对于python 3.x:

$ cd /opt/local/Library/Frameworks/Python.framework/Versions/3.4/bin
$ sudo ./ipython kernelspec install-self

现在,您可以打开一个Ipython笔记本,然后选择python 2.x或python 3.x笔记本。

A solution is available that allows me to keep my MacPorts installation by configuring the Ipython kernelspec.

Requirements:

  • MacPorts is installed in the usual /opt directory
  • python 2.7 is installed through macports
  • python 3.4 is installed through macports
  • Ipython is installed for python 2.7
  • Ipython is installed for python 3.4

For python 2.x:

$ cd /opt/local/Library/Frameworks/Python.framework/Versions/2.7/bin
$ sudo ./ipython kernelspec install-self

For python 3.x:

$ cd /opt/local/Library/Frameworks/Python.framework/Versions/3.4/bin
$ sudo ./ipython kernelspec install-self

Now you can open an Ipython notebook and then choose a python 2.x or a python 3.x notebook.


回答 5

通过我的Linux安装,我做到了:

sudo ipython2 kernelspec install-self

现在,我的python 2又回到了列表中。

参考:

http://ipython.readthedocs.org/en/latest/install/kernel_install.html


更新:

上面的方法现已弃用,将来会被删除。新方法应为:

sudo ipython2 kernel install

From my Linux installation I did:

sudo ipython2 kernelspec install-self

And now my python 2 is back on the list.

Reference:

http://ipython.readthedocs.org/en/latest/install/kernel_install.html


UPDATE:

The method above is now deprecated and will be dropped in the future. The new method should be:

sudo ipython2 kernel install


回答 6

以下是将python2内核添加到jupyter笔记本的步骤:

打开一个终端并创建一个新的python 2环境: conda create -n py27 python=2.7

激活环境:Linux source activate py27或Windowsactivate py27

在环境中安装内核: conda install notebook ipykernel

在env外部安装内核: ipython kernel install --user

关闭环境: source deactivate

尽管答案很晚,希望有人发现它有用:p

Following are the steps to add the python2 kernel to jupyter notebook::

open a terminal and create a new python 2 environment: conda create -n py27 python=2.7

activate the environment: Linux source activate py27 or windows activate py27

install the kernel in the env: conda install notebook ipykernel

install the kernel for outside the env: ipython kernel install --user

close the env: source deactivate

Although a late answer hope someone finds it useful :p


回答 7

使用sudo pip3 install jupyter安装了python3 jupyter和sudo pip install jupyter安装jupyter笔记本python2。然后,您可以调用ipython kernel install命令来启用两种类型的笔记本以在jupyter笔记本中进行选择。

Use sudo pip3 install jupyter for installing jupyter for python3 and sudo pip install jupyter for installing jupyter notebook for python2. Then, you can call ipython kernel install command to enable both types of notebook to choose from in jupyter notebook.


回答 8

我查看了这个出色的信息,然后想知道

  1. 我已经安装了python2,python3和IPython,
  2. 我安装了PyCharm,
  3. PyCharm将IPython用于其Python控制台,

如果 PyCharm将使用

  1. IPython的-PY2时菜单>文件>设置>项目>项目解释== PY2
  2. 当菜单>文件>设置>项目>项目解释器== py3时,IPython-py3

答案:是的!

PS我也安装了适用于Windows的Python启动器。

I looked at this excellent info and then wondered, since

  1. i have python2, python3 and IPython all installed,
  2. i have PyCharm installed,
  3. PyCharm uses IPython for its Python Console,

if PyCharm would use

  1. IPython-py2 when Menu>File>Settings>Project>Project Interpreter == py2 AND
  2. IPython-py3 when Menu>File>Settings>Project>Project Interpreter == py3

ANSWER: Yes!

P.S. i have Python Launcher for Windows installed as well.


回答 9

在Windows 7下,我安装了anaconda和anaconda3。我走进去\Users\me\anaconda\Scripts执行

sudo .\ipython kernelspec install-self

然后我走进去\Users\me\anaconda3\Scripts执行

sudo .\ipython kernel install

(我知道了 jupyter kernelspec install-self is DEPRECATED as of 4.0. You probably want 'ipython kernel install' to install the IPython kernelspec.

启动后jupyter notebook(在anaconda3中),我在右上角的“新建”下获得了一个整洁的下拉菜单,让我在Python 2 odr和Python 3内核之间进行选择。

Under Windows 7 I had anaconda and anaconda3 installed. I went into \Users\me\anaconda\Scripts and executed

sudo .\ipython kernelspec install-self

then I went into \Users\me\anaconda3\Scripts and executed

sudo .\ipython kernel install

(I got jupyter kernelspec install-self is DEPRECATED as of 4.0. You probably want 'ipython kernel install' to install the IPython kernelspec.)

After starting jupyter notebook (in anaconda3) I got a neat dropdown menu in the upper right corner under “New” letting me choose between Python 2 odr Python 3 kernels.


回答 10

  • 如果您在虚拟环境中运行anaconda。
  • 当您创建一个新笔记本时,我没有显示选择虚拟环境内核。
  • 然后,您必须使用以下命令将其设置到ipykernel中
$ pip install --user ipykernel
$ python -m ipykernel install --user --name=test2
  • If you are running anaconda in virtual environment.
  • And when you create a new notebook but i’s not showing to select the virtual environment kernel.
  • Then you have to set it into the ipykernel using the following command
$ pip install --user ipykernel
$ python -m ipykernel install --user --name=test2

如何将文本文件(.py)加载/编辑/运行/保存到IPython Notebook单元中?

问题:如何将文本文件(.py)加载/编辑/运行/保存到IPython Notebook单元中?

我最近已将使用IPython笔记本作为工作流程的一部分。但是,我没有成功找到一种方法来将.py文件导入打开的IPython Notebook的各个单元中,以便可以对其进行编辑,运行和保存。能做到吗?

我在文档中找到了这一点,该文档告诉我如何将.py文件作为新笔记本导入,但是这与我想要实现的目标不符。

任何建议将不胜感激。

I’ve recently moved over to using IPython notebooks as part of my workflow. However, I’ve not been successful in finding a way to import .py files into the individual cells of an open IPython notebook so that they can edited, run and then saved. Can this be done?

I’ve found this in the documentation which tells me how to import .py files as new notebooks but this falls short of what I want to achieve.

Any suggestions would be much appreciated.


回答 0

编辑:从IPython 3(现在为Jupyter项目)开始,笔记本具有文本编辑器,可以用作加载/编辑/保存文本文件的更方便的替代方法。

可以使用magic命令将文本文件加载到笔记本单元中%load

如果执行包含以下内容的单元格:

%load filename.py

的内容filename.py将在下一个单元格中加载。您可以照常编辑和执行它。

要将单元格内容保存回文件中,请在单元格%%writefile filename.py的开头添加cell-magic 并运行它。请注意,如果已经存在同名文件,它将被静默覆盖

要查看任何魔术命令的帮助,请添加?:like %load?%%writefile?

有关魔术功能的常规帮助,请键入“%magic”。有关可用魔术功能的列表,请使用%lsmagic。对于其中任何一个的描述,请键入%magic_name ?,例如’%cd?’。

另请参见:官方IPython文档中的Magic函数

EDIT: Starting from IPython 3 (now Jupyter project), the notebook has a text editor that can be used as a more convenient alternative to load/edit/save text files.

A text file can be loaded in a notebook cell with the magic command %load.

If you execute a cell containing:

%load filename.py

the content of filename.py will be loaded in the next cell. You can edit and execute it as usual.

To save the cell content back into a file add the cell-magic %%writefile filename.py at the beginning of the cell and run it. Beware that if a file with the same name already exists it will be silently overwritten.

To see the help for any magic command add a ?: like %load? or %%writefile?.

For general help on magic functions type “%magic” For a list of the available magic functions, use %lsmagic. For a description of any of them, type %magic_name?, e.g. ‘%cd?’.

See also: Magic functions from the official IPython docs.


回答 1

写入/保存

%%writefile myfile.py

  • 将单元格内容写入/保存到myfile.py中(用于-a追加)。另一个别名:%%file myfile.py

跑步

%run myfile.py

  • 运行myfile.py并在当前单元格中输出结果

加载/导入

%load myfile.py

  • 将“导入” myfile.py加载到当前单元格中

寻求更多的魔术和帮助

%lsmagic

  • 列出所有其他酷单元魔术命令。

%COMMAND-NAME?

  • 获取有关如何使用特定命令的帮助。即%run?

注意

除了单元魔术命令之外,IPython Notebook(现在为Jupyter笔记本)非常酷,它允许您直接使用单元中的任何Unix命令(这也等同于使用%%bashcell magic命令)。

要从单元格运行unix命令,只需在命令前加上!标记。例如:

  • !python --version 查看您的python版本
  • !python myfile.py运行myfile.py并在当前单元格中输出结果,就像%run(请参阅!python%run下面的注释之间的区别)一样。

另外,请参阅此nbviewer以获取有关示例的进一步说明。希望这可以帮助。

To write/save

%%writefile myfile.py

  • write/save cell contents into myfile.py (use -a to append). Another alias: %%file myfile.py

To run

%run myfile.py

  • run myfile.py and output results in the current cell

To load/import

%load myfile.py

  • load “import” myfile.py into the current cell

For more magic and help

%lsmagic

  • list all the other cool cell magic commands.

%COMMAND-NAME?

  • for help on how to use a certain command. i.e. %run?

Note

Beside the cell magic commands, IPython notebook (now Jupyter notebook) is so cool that it allows you to use any unix command right from the cell (this is also equivalent to using the %%bash cell magic command).

To run a unix command from the cell, just precede your command with ! mark. for example:

  • !python --version see your python version
  • !python myfile.py run myfile.py and output results in the current cell, just like %run (see the difference between !python and %run in the comments below).

Also, see this nbviewer for further explanation with examples. Hope this helps.


回答 2

将一个Python文件拖放到Ipython笔记本的“ home”笔记本表中,单击“上传”。这将创建一个只有一个包含.py文件内容的单元格的新笔记本

从您喜欢的编辑器中进行其他复制/粘贴;)

Drag and drop a Python file in the Ipython notebooks “home” notebooks table, click upload. This will create a new notebook with only one cell containing your .py file content

Else copy/paste from your favorite editor ;)


回答 3

我发现在ipython笔记本中使用ls和cd查找文件是令人满意的。然后,在单元格中键入cat your_file_name,您将获得文件的内容,然后可以将其作为代码粘贴到单元格中。

I have found it satisfactory to use ls and cd within ipython notebook to find the file. Then type cat your_file_name into the cell, and you’ll get back the contents of the file, which you can then paste into the cell as code.


如何在Jupyter Notebook中放大内联图?

问题:如何在Jupyter Notebook中放大内联图?

我已在我的Ipython Notebook上使用“ %matplotlib inline” 内嵌我的图。

现在,该图出现。但是,它很小。有没有办法使用笔记本设置或绘图设置使其显得更大?

I have made my plots inline on my Ipython Notebook with “%matplotlib inline.”

Now, the plot appears. However, it is very small. Is there a way to make it appear larger using either notebook settings or plot settings?


回答 0

是的,figuresize像这样玩(在调用子图之前):

fig=plt.figure(figsize=(18, 16), dpi= 80, facecolor='w', edgecolor='k')

Yes, play with figuresize and dpi like so (before you call your subplot):

fig=plt.figure(figsize=(12,8), dpi= 100, facecolor='w', edgecolor='k')

As @tacaswell and @Hagne pointed out, you can also change the defaults if it’s not a one-off:

plt.rcParams['figure.figsize'] = [12, 8]
plt.rcParams['figure.dpi'] = 100 # 200 e.g. is really fine, but slower

回答 1

默认图形大小(以英寸为单位)由

matplotlib.rcParams['figure.figsize'] = [width, height]

例如:

import matplotlib.pyplot as plt
plt.rcParams['figure.figsize'] = [10, 5]

创建一个10(宽)x 5(高)英寸的图形

The default figure size (in inches) is controlled by

matplotlib.rcParams['figure.figsize'] = [width, height]

For example:

import matplotlib.pyplot as plt
plt.rcParams['figure.figsize'] = [10, 5]

creates a figure with 10 (width) x 5 (height) inches


回答 2

我发现 %matplotlib notebook与内联Jupyter笔记本相比,这种方法对我来说更好。

请注意,如果您以前使用%matplotlib inline过,则可能需要重新启动内核。

2019年更新:如果您正在运行Jupyter Lab,则可能要使用 %matplotlib widget

I have found that %matplotlib notebook works better for me than inline with Jupyter notebooks.

Note that you may need to restart the kernel if you were using %matplotlib inline before.

Update 2019: If you are running Jupyter Lab you might want to use %matplotlib widget


回答 3

如果您只希望图形显示更大而不改变图形的一般外观,则可以提高图形分辨率。根据大多数其他答案中的建议更改图形大小会改变外观,因为字体大小不会相应缩放。

import matplotlib.pylab as plt
plt.rcParams['figure.dpi'] = 200

If you only want the image of your figure to appear larger without changing the general appearance of your figure increase the figure resolution. Changing the figure size as suggested in most other answers will change the appearance since font sizes do not scale accordingly.

import matplotlib.pylab as plt
plt.rcParams['figure.dpi'] = 200

回答 4

问题是关于matplotlib,但是为了所有最终在此处获得与语言无关的标题的R用户的缘故:

如果您使用的是R内核,则只需使用:

options(repr.plot.width=4, repr.plot.height=3)

The question is about matplotlib, but for the sake of any R users that end up here given the language-agnostic title:

If you’re using an R kernel, just use:

options(repr.plot.width=4, repr.plot.height=3)

回答 5

调整一个图形的大小:

import matplotlib.pyplot as plt

fig=plt.figure(figsize=(15, 15))

要更改默认设置,从而更改所有图,请执行以下操作:

import matplotlib.pyplot as plt

plt.rcParams['figure.figsize'] = [15, 15]

To adjust the size of one figure:

import matplotlib.pyplot as plt

fig=plt.figure(figsize=(15, 15))

To change the default settings, and therefore all your plots:

import matplotlib.pyplot as plt

plt.rcParams['figure.figsize'] = [15, 15]


回答 6

一次性调整图形大小的一个小而重要的细节(如上述几位评论者所说,“这对我不起作用”):

您应该在定义实际图之前做plt.figure(figsize =(,))。例如:

这应该根据您指定的figsize正确调整图的大小:

values = [1,1,1,2,2,3]
_ = plt.figure(figsize=(10,6))
_ = plt.hist(values,bins=3)
plt.show()

而这将显示具有默认设置的图,似乎“忽略”了figsize:

values = [1,1,1,2,2,3]
_ = plt.hist(values,bins=3)
_ = plt.figure(figsize=(10,6))
plt.show()

A small but important detail for adjusting figure size on a one-off basis (as several commenters above reported “this doesn’t work for me”):

You should do plt.figure(figsize=(,)) PRIOR to defining your actual plot. For example:

This should correctly size the plot according to your specified figsize:

values = [1,1,1,2,2,3]
_ = plt.figure(figsize=(10,6))
_ = plt.hist(values,bins=3)
plt.show()

Whereas this will show the plot with the default settings, seeming to “ignore” figsize:

values = [1,1,1,2,2,3]
_ = plt.hist(values,bins=3)
_ = plt.figure(figsize=(10,6))
plt.show()

在IPython中重新加载子模块

问题:在IPython中重新加载子模块

目前,我正在处理一个包含子模块并使用numpy / scipy的python项目。Ipython用作交互式控制台。不幸的是,我对现在使用的工作流程不是很满意,请多多指教。

在IPython中,该框架是通过一个简单的import命令加载的。但是,通常有必要在框架的子模块之一中更改代码。至此,已经加载了一个模型,并且我使用IPython与之交互。

现在,该框架包含许多相互依赖的模块,即,在最初加载该框架时,主模块正在导入和配置子模块。仅当使用重新加载模块时,才执行对代码的更改reload(main_mod.sub_mod)。这很麻烦,因为我需要使用完整路径分别重新加载所有更改的模块。如果reload(main_module)还重新加载所有子模块,但又不重新加载numpy / scipy ,将非常方便。

Currently I am working on a python project that contains sub modules and uses numpy/scipy. Ipython is used as interactive console. Unfortunately I am not very happy with workflow that I am using right now, I would appreciate some advice.

In IPython, the framework is loaded by a simple import command. However, it is often necessary to change code in one of the submodules of the framework. At this point a model is already loaded and I use IPython to interact with it.

Now, the framework contains many modules that depend on each other, i.e. when the framework is initially loaded the main module is importing and configuring the submodules. The changes to the code are only executed if the module is reloaded using reload(main_mod.sub_mod). This is cumbersome as I need to reload all changed modules individually using the full path. It would be very convenient if reload(main_module) would also reload all sub modules, but without reloading numpy/scipy..


回答 0

IPython带有一些自动重装魔术:

%load_ext autoreload
%autoreload 2

每次执行新行之前,它将重新加载所有更改的模块。它的工作方式与稍有不同dreload。有一些警告,请键入%autoreload?以查看可能出问题的地方。


如果要始终启用此设置,请修改IPython配置文件~/.ipython/profile_default/ipython_config.py[1]并附加:

c.InteractiveShellApp.extensions = ['autoreload']     
c.InteractiveShellApp.exec_lines = ['%autoreload 2']

通过下面的评论归功于@Kos。

[1]如果您没有该文件~/.ipython/profile_default/ipython_config.py,则需要先调用ipython profile create。或者文件可能位于$IPYTHONDIR

IPython comes with some automatic reloading magic:

%load_ext autoreload
%autoreload 2

It will reload all changed modules every time before executing a new line. The way this works is slightly different than dreload. Some caveats apply, type %autoreload? to see what can go wrong.


If you want to always enable this settings, modify your IPython configuration file ~/.ipython/profile_default/ipython_config.py[1] and appending:

c.InteractiveShellApp.extensions = ['autoreload']     
c.InteractiveShellApp.exec_lines = ['%autoreload 2']

Credit to @Kos via a comment below.

[1] If you don’t have the file ~/.ipython/profile_default/ipython_config.py, you need to call ipython profile create first. Or the file may be located at $IPYTHONDIR.


回答 1

在IPython 0.12(可能更早)中,您可以使用以下命令:

%load_ext autoreload
%autoreload 2

这与pv的答案基本相同,除了扩展名已重命名并现在使用加载%load_ext

In IPython 0.12 (and possibly earlier), you can use this:

%load_ext autoreload
%autoreload 2

This is essentially the same as the answer by pv., except that the extension has been renamed and is now loaded using %load_ext.


回答 2

由于某种原因,当您将代码从一个笔记本导入另一个笔记本时,这两种方法都不起作用%autoreload,也dreload似乎不起作用。只有普通的Python 可以工作:reload

reload(module)

基于[1]

For some reason, neither %autoreload, nor dreload seem to work for the situation when you import code from one notebook to another. Only plain Python reload works:

reload(module)

Based on [1].


回答 3

IPython提供dreload()了递归方式重新加载所有子模块。就个人而言,我更喜欢使用%run()magic命令(尽管它不会执行深度重新加载,正如John Salvatier在评论中指出的那样)。

IPython offers dreload() to recursively reload all submodules. Personally, I prefer to use the %run() magic command (though it does not perform a deep reload, as pointed out by John Salvatier in the comments).


回答 4

名为importliballow的模块可以访问导入内部构件。特别是,它提供功能importlib.reload()

import importlib
importlib.reload(my_module)

与此相反%autoreloadimportlib.reload()还重置模块中设置的全局变量。在大多数情况下,这就是您想要的。

importlib仅从Python 3.1开始可用。对于旧版本,您必须使用module imp

Module named importlib allow to access to import internals. Especially, it provide function importlib.reload():

import importlib
importlib.reload(my_module)

In contrary of %autoreload, importlib.reload() also reset global variables set in module. In most cases, it is what you want.

importlib is only available since Python 3.1. For older version, you have to use module imp.


回答 5

http://shawnleezx.github.io/blog/2015/08/03/some-notes-on-ipython-startup-script/

为了避免一遍又一遍地输入这些魔术函数,可以将它们放在ipython启动脚本中(用.ipython / profile_default / startup下的.py后缀命名。该文件夹下的所有python脚本将按照词法顺序加载),看起来如下:

from IPython import get_ipython
ipython = get_ipython()

ipython.magic("pylab")
ipython.magic("load_ext autoreload")
ipython.magic("autoreload 2")

http://shawnleezx.github.io/blog/2015/08/03/some-notes-on-ipython-startup-script/

To avoid typing those magic function again and again, they could be put in the ipython startup script(Name it with .py suffix under .ipython/profile_default/startup. All python scripts under that folder will be loaded according to lexical order), which looks like the following:

from IPython import get_ipython
ipython = get_ipython()

ipython.magic("pylab")
ipython.magic("load_ext autoreload")
ipython.magic("autoreload 2")

回答 6

这个怎么样:

import inspect

# needs to be primed with an empty set for loaded
def recursively_reload_all_submodules(module, loaded=None):
    for name in dir(module):
        member = getattr(module, name)
        if inspect.ismodule(member) and member not in loaded:
            recursively_reload_all_submodules(member, loaded)
    loaded.add(module)
    reload(module)

import mymodule
recursively_reload_all_submodules(mymodule, set())

这样可以有效地重新加载您为其提供的整个模块树和子模块树。您也可以将此函数放在.ipythonrc中(我认为),以便每次启动解释器时都将其加载。

How about this:

import inspect

# needs to be primed with an empty set for loaded
def recursively_reload_all_submodules(module, loaded=None):
    for name in dir(module):
        member = getattr(module, name)
        if inspect.ismodule(member) and member not in loaded:
            recursively_reload_all_submodules(member, loaded)
    loaded.add(module)
    reload(module)

import mymodule
recursively_reload_all_submodules(mymodule, set())

This should effectively reload the entire tree of modules and submodules you give it. You can also put this function in your .ipythonrc (I think) so it is loaded every time you start the interpreter.


回答 7

另外一个选项:

$ cat << EOF > ~/.ipython/profile_default/startup/50-autoreload.ipy
%load_ext autoreload
%autoreload 2
EOF

在Ubuntu 14.04上的ipython和ipython3 v5.1.0上进行了验证。

Another option:

$ cat << EOF > ~/.ipython/profile_default/startup/50-autoreload.ipy
%load_ext autoreload
%autoreload 2
EOF

Verified on ipython and ipython3 v5.1.0 on Ubuntu 14.04.


回答 8

我的重载标准做法是在首次打开时将两种方法结合起来IPython

from IPython.lib.deepreload import reload
%load_ext autoreload
%autoreload 2

在执行此操作之前加载模块将导致即使使用手册也无法重新加载它们reload(module_name)。我仍然很少遇到类方法无法重装的莫名其妙的问题,而我尚未研究过。

My standard practice for reloading is to combine both methods following first opening of IPython:

from IPython.lib.deepreload import reload
%load_ext autoreload
%autoreload 2

Loading modules before doing this will cause them not to be reloaded, even with a manual reload(module_name). I still, very rarely, get inexplicable problems with class methods not reloading that I’ve not yet looked into.


回答 9

请注意,autoreload如果您手动保存更改的文件(例如,使用ctrl + s或cmd + s),则上述内容仅在IntelliJ中有效。自动保存似乎不起作用。

Note that the above mentioned autoreload only works in IntelliJ if you manually save the changed file (e.g. using ctrl+s or cmd+s). It doesn’t seem to work with auto-saving.


回答 10

在Anaconda的Jupyter笔记本上,执行以下操作:

%load_ext autoreload
%autoreload 2

产生了消息:

autoreload扩展程序已加载。要重新加载它,请使用: %reload_ext autoreload

看起来最好这样做:

%reload_ext autoreload
%autoreload 2

版本信息:

笔记本服务器的版本为5.0.0,并且运行在:Python 3.6.2 | Anaconda,Inc. | (默认值,2017年9月20日,13:35:58)[MSC v.1900 32位(Intel)]

On Jupyter Notebooks on Anaconda, doing this:

%load_ext autoreload
%autoreload 2

produced the message:

The autoreload extension is already loaded. To reload it, use: %reload_ext autoreload

It looks like it’s preferable to do:

%reload_ext autoreload
%autoreload 2

Version information:

The version of the notebook server is 5.0.0 and is running on: Python 3.6.2 |Anaconda, Inc.| (default, Sep 20 2017, 13:35:58) [MSC v.1900 32 bit (Intel)]


回答 11

此操作将不会重新加载任何子对象,我相信您必须为此使用IPython的deepreload。

Any subobjects will not be reloaded by this, I believe you have to use IPython’s deepreload for that.


如何在浏览器中增加Jupyter / ipython笔记本的单元格宽度?

问题:如何在浏览器中增加Jupyter / ipython笔记本的单元格宽度?

我想在浏览器中增加ipython笔记本的宽度。我有一个高分辨率的屏幕,我想扩展单元格的宽度/大小以利用这个额外的空间。

谢谢!


编辑:5/2017

我现在使用jupyterthemes:https : //github.com/dunovank/jupyter-themes

和此命令:

jt -t oceans16 -f roboto -fs 12 -cellw 100%

可以将宽度设置为100%,并且主题很好。

I would like to increase the width of the ipython notebook in my browser. I have a high-resolution screen, and I would like to expand the cell width/size to make use of this extra space.

Thanks!


edit: 5/2017

I now use jupyterthemes: https://github.com/dunovank/jupyter-themes

and this command:

jt -t oceans16 -f roboto -fs 12 -cellw 100%

which sets the width to 100% with a nice theme.


回答 0

如果您不想更改默认设置,而只想更改正在使用的当前笔记本的宽度,则可以在单元格中输入以下内容:

from IPython.core.display import display, HTML
display(HTML("<style>.container { width:100% !important; }</style>"))

If you don’t want to change your default settings, and you only want to change the width of the current notebook you’re working on, you can enter the following into a cell:

from IPython.core.display import display, HTML
display(HTML("<style>.container { width:100% !important; }</style>"))

回答 1

div.cell解决方案实际上不适用于我的IPython,但是幸运的是有人提出了适用于新IPython的可行解决方案:

创建包含内容的文件~/.ipython/profile_default/static/custom/custom.css(iPython)或~/.jupyter/custom/custom.css(Jupyter)

.container { width:100% !important; }

然后重新启动iPython / Jupyter笔记本。请注意,这将影响所有笔记本电脑。

That div.cell solution didn’t actually work on my IPython, however luckily someone suggested a working solution for new IPythons:

Create a file ~/.ipython/profile_default/static/custom/custom.css (iPython) or ~/.jupyter/custom/custom.css (Jupyter) with content

.container { width:100% !important; }

Then restart iPython/Jupyter notebooks. Note that this will affect all notebooks.


回答 2

为了使它与jupyter(版本4.0.6)一起使用,我创建了以下内容~/.jupyter/custom/custom.css

/* Make the notebook cells take almost all available width */
.container {
    width: 99% !important;
}   

/* Prevent the edit cell highlight box from getting clipped;
 * important so that it also works when cell is in edit mode*/
div.cell.selected {
    border-left-width: 1px !important;
}

To get this to work with jupyter (version 4.0.6) I created ~/.jupyter/custom/custom.css containing:

/* Make the notebook cells take almost all available width */
.container {
    width: 99% !important;
}   

/* Prevent the edit cell highlight box from getting clipped;
 * important so that it also works when cell is in edit mode*/
div.cell.selected {
    border-left-width: 1px !important;
}

回答 3

是时候使用jupyterlab

最后,笔记本电脑急需升级。默认情况下,它使用窗口的整个宽度,就像其他任何成熟的本机IDE一样。

您要做的就是:

pip install jupyterlab
# if you use conda
conda install -c conda-forge jupyterlab
# to run 
jupyter lab    # instead of jupyter notebook

这是blog.Jupyter.org的屏幕截图

It’s time to use jupyterlab

Finally, a much-needed upgrade has come to notebooks. By default, it uses the full width of your window like any other full-fledged native IDE.

All you have to do is:

pip install jupyterlab
# if you use conda
conda install -c conda-forge jupyterlab
# to run 
jupyter lab    # instead of jupyter notebook

Here is a screenshot from blog.Jupyter.org


回答 4

全新安装后,我通常要做的是修改存储所有视觉样式的主css文件。我使用Miniconda,但位置与其他人相似C:\Miniconda3\Lib\site-packages\notebook\static\style\style.min.css

在某些屏幕上,这些分辨率是不同的,并且大于1。为安全起见,我将所有分辨率更改为98%,因此,如果从笔记本电脑上的外接屏幕断开连接,则屏幕宽度仍为98%。

然后,将1140px替换为屏幕宽度的98%

@media (min-width: 1200px) {
  .container {
    width: 1140px;
  }
}

编辑后

@media (min-width: 1200px) {
  .container {
    width: 98%;
  }
}

保存并重新启动笔记本


更新资料

最近不得不在已安装的环境中扩展Jupyter单元,这导致我回到这里提醒自己。

如果您需要在虚拟环境中进行安装,请先安装jupyter。您可以在此子目录中找到css文件

env/lib/python3.6/site-packages/notebook/static/style/stye.min.css

What I do usually after new installation is to modify the main css file where all visual styles are stored. I use Miniconda but location is similar with others C:\Miniconda3\Lib\site-packages\notebook\static\style\style.min.css

With some screens these resolutions are different and more than 1. To be on the safe side I change all to 98% so if I disconnect from my external screens on my laptop I still have 98% screen width.

Then just replace 1140px with 98% of the screen width.

@media (min-width: 1200px) {
  .container {
    width: 1140px;
  }
}

After editing

@media (min-width: 1200px) {
  .container {
    width: 98%;
  }
}

Save and restart your notebook


Update

Recently had to wider Jupyter cells on an environment it is installed, which led me to come back here and remind myself.

If you need to do it in virtual env you installed jupyter on. You can find the css file in this subdir

env/lib/python3.6/site-packages/notebook/static/style/stye.min.css

回答 5

您可以通过从任何单元格调用样式表来设置笔记本的CSS。作为示例,请看Navier Stokes类12个步骤

特别是,创建一个包含

<style>
    div.cell{
        width:100%;
        margin-left:1%;
        margin-right:auto;
    }
</style>

应该给你一个起点。但是,可能有必要也进行调整,例如div.text_cell_render处理降价和代码单元。

如果是该文件,custom.css则添加包含以下内容的单元格:

from IPython.core.display import HTML
def css_styling():
    styles = open("custom.css", "r").read()
    return HTML(styles)
css_styling()

这将应用所有样式,尤其是更改像元宽度。

You can set the CSS of a notebook by calling a stylesheet from any cell. As an example, take a look at the 12 Steps to Navier Stokes course.

In particular, creating a file containing

<style>
    div.cell{
        width:100%;
        margin-left:1%;
        margin-right:auto;
    }
</style>

should give you a starting point. However, it may be necessary to also adjust e.g div.text_cell_render to deal with markdown as well as code cells.

If that file is custom.css then add a cell containing:

from IPython.core.display import HTML
def css_styling():
    styles = open("custom.css", "r").read()
    return HTML(styles)
css_styling()

This will apply all the stylings, and, in particular, change the cell width.


回答 6

(从2018年开始,我建议您尝试使用JupyterHub / JupyterLab。它使用监视器的整个宽度。如果这不是一种选择,则可能是因为您使用的是基于云的Jupyter即服务提供商,继续阅读)

(时尚被指控窃取用户数据,我已改为使用Stylus插件)

我建议使用时尚浏览器插件。这样,您可以覆盖所有笔记本的css,而无需向笔记本中添加任何代码。我们不喜欢在.ipython / profile_default中更改配置,因为我们正在为整个团队运行共享的Jupyter服务器,并且宽度是用户首选项。

我专门为垂直方向的高分辨率屏幕设计了一种样式,该样式使单元格变宽,并在底部添加了一些空白区域,因此您可以将最后一个单元格放置在屏幕的中央。 https://userstyles.org/styles/131230/jupyter-wide 当然,如果您使用其他布局,或者您不希望最后有多余的空格,则可以根据自己的喜好修改我的CSS。

最后但并非最不重要的一点是,Stylish是包含在工具集中的出色工具,因为您可以根据自己的喜好轻松自定义其他站点/工具(例如Jira,Podio,Slack等)。

@media (min-width: 1140px) {
  .container {
    width: 1130px;
  }
}

.end_space {
  height: 800px;
}

(As of 2018, I would advise trying out JupyterHub/JupyterLab. It uses the full width of the monitor. If this is not an option, maybe since you are using one of the cloud-based Jupyter-as-a-service providers, keep reading)

(Stylish is accused of stealing user data, I have moved on to using Stylus plugin instead)

I recommend using Stylish Browser Plugin. This way you can override css for all notebooks, without adding any code to notebooks. We don’t like to change configuration in .ipython/profile_default, since we are running a shared Jupyter server for the whole team and width is a user preference.

I made a style specifically for vertically-oriented high-res screens, that makes cells wider and adds a bit of empty-space in the bottom, so you can position the last cell in the centre of the screen. https://userstyles.org/styles/131230/jupyter-wide You can, of course, modify my css to your liking, if you have a different layout, or you don’t want extra empty-space in the end.

Last but not least, Stylish is a great tool to have in your toolset, since you can easily customise other sites/tools to your liking (e.g. Jira, Podio, Slack, etc.)

@media (min-width: 1140px) {
  .container {
    width: 1130px;
  }
}

.end_space {
  height: 800px;
}

回答 7

对于Chrome用户,我建议使用Stylebot,它可以让您覆盖任何页面上的所有CSS,还可以搜索和安装其他共享自定义CSS。但是,出于我们的目的,我们不需要任何高级主题。打开Stylebot,更改为Edit CSS。Jupyter捕获了一些击键,因此您将无法在其中键入以下代码。只需复制和粘贴,或者仅编辑即可:

#notebook-container.container {
    width: 90%;
}

根据需要更改宽度,我发现90%的外观比100%的外观好。但这完全取决于您。

For Chrome users, I recommend Stylebot, which will let you override any CSS on any page, also let you search and install other share custom CSS. However, for our purpose we don’t need any advance theme. Open Stylebot, change to Edit CSS. Jupyter captures some keystrokes, so you will not be able to type the code below in. Just copy and paste, or just your editor:

#notebook-container.container {
    width: 90%;
}

Change the width as you like, I find 90% looks nicer than 100%. But it is totally up to your eye.


回答 8

这是我最终使用的代码。它将输入和输出单元格向左和向右拉伸。请注意,输入/输出编号指示将消失:

from IPython.core.display import display, HTML
display(HTML("<style>.container { width:100% !important; }</style>"))
display(HTML("<style>.output_result { max-width:100% !important; }</style>"))
display(HTML("<style>.prompt { display:none !important; }</style>"))

This is the code I ended up using. It stretches input & output cells to the left and right. Note that the input/output number indication will be gone:

from IPython.core.display import display, HTML
display(HTML("<style>.container { width:100% !important; }</style>"))
display(HTML("<style>.output_result { max-width:100% !important; }</style>"))
display(HTML("<style>.prompt { display:none !important; }</style>"))

回答 9

我对@ jvd10的解决方案进行了一些修改。“!important”似乎太强了,以至于显示TOC侧栏时容器不能很好地适应。我将其删除并添加了“最小宽度”以限制最小宽度。

这是我的.juyputer / custom / custom.css:

/* Make the notebook cells take almost all available width and limit minimal width to 1110px */
.container {
    width: 99%;
    min-width: 1110px;
}   

/* Prevent the edit cell highlight box from getting clipped;
 * important so that it also works when cell is in edit mode*/
div.cell.selected {
    border-left-width: 1px;
}

I made some modification to @jvd10’s solution. The ‘!important’ seems too strong that the container doesn’t adapt well when TOC sidebar is displayed. I removed it and added ‘min-width’ to limit the minimal width.

Here is my .juyputer/custom/custom.css:

/* Make the notebook cells take almost all available width and limit minimal width to 1110px */
.container {
    width: 99%;
    min-width: 1110px;
}   

/* Prevent the edit cell highlight box from getting clipped;
 * important so that it also works when cell is in edit mode*/
div.cell.selected {
    border-left-width: 1px;
}

回答 10

我尝试了一切,但对我没有用,最终我将数据框显示为HTML,如下所示

from IPython.display import HTML    
HTML (pd.to_html())

I tried everything and nothing worked for me, I ended up using displaying my data frame as HTML as follows

from IPython.display import HTML    
HTML (pd.to_html())

回答 11

对于Firefox / Chrome用户,一种实现100%宽度的好方法是使用自定义TamperMonkey脚本。

好处是

  1. 在浏览器中配置一次,无需修改服务器配置。
  2. 与多个jupyter服务器一起使用。
  3. TamperMonkey受信任,维护且稳定。
  4. 通过javascript可以进行许多其他自定义。

该脚本对我有用https://gist.githubusercontent.com/mrk-andreev/2a9c2538fad0b687c27e192d5948834f/raw/6aa1148573dc20a22fca126e56e3b03f4abf281b/jpn_tmonkey.js

For Firefox/Chrome users, a nice way to achieve 100% width is to use a custom TamperMonkey script.

The benefits are

  1. configure this once in your browser, no need to modify the server configuration.
  2. works with multiple jupyter servers.
  3. TamperMonkey is trusted, maintained, and stable.
  4. Lots of additional customization is possible via javascript.

This script works for me https://gist.githubusercontent.com/mrk-andreev/2a9c2538fad0b687c27e192d5948834f/raw/6aa1148573dc20a22fca126e56e3b03f4abf281b/jpn_tmonkey.js


“%matplotlib内联”的目的

问题:“%matplotlib内联”的目的

有人可以向我解释到底有什么用%matplotlib inline吗?

Could someone explain to me what exactly is the use of %matplotlib inline?


回答 0

%matplotlib是IPython中的魔术函数。为了方便起见,我在这里引用相关文档供您阅读:

IPython有一组预定义的“魔术函数”,您可以使用命令行样式的语法来调用它们。有两种魔术,面向行的和面向单元的。换行符以%字符作为前缀,其工作方式与OS命令行调用非常相似:它们作为行的其余部分作为参数,其中的参数传递时不带括号或引号。线魔术可以返回结果,并且可以在作业的右侧使用。单元格魔术的前缀为%%,并且它们是函数,它们不仅作为该行的其余部分作为参数,而且还作为单独的参数作为其下方的行的参数。

%matplotlib inline 将matplotlib的后端设置为’inline’后端

使用此后端,绘图命令的输出将在Jupyter笔记本之类的前端内联显示,直接位于生成它的代码单元下方。然后,生成的图也将存储在笔记本文档中。

使用“内联”后端时,您的matplotlib图将包含在笔记本中代码旁边。还可能值得阅读如何内联制作IPython笔记本matplotlib绘图,以获取有关如何在代码中使用它的参考。

如果你想交互,以及,你可以使用nbagg后端%matplotlib notebook(在IPython中3.X),如所描述这里

%matplotlib is a magic function in IPython. I’ll quote the relevant documentation here for you to read for convenience:

IPython has a set of predefined ‘magic functions’ that you can call with a command line style syntax. There are two kinds of magics, line-oriented and cell-oriented. Line magics are prefixed with the % character and work much like OS command-line calls: they get as an argument the rest of the line, where arguments are passed without parentheses or quotes. Lines magics can return results and can be used in the right hand side of an assignment. Cell magics are prefixed with a double %%, and they are functions that get as an argument not only the rest of the line, but also the lines below it in a separate argument.

%matplotlib inline sets the backend of matplotlib to the ‘inline’ backend:

With this backend, the output of plotting commands is displayed inline within frontends like the Jupyter notebook, directly below the code cell that produced it. The resulting plots will then also be stored in the notebook document.

When using the ‘inline’ backend, your matplotlib graphs will be included in your notebook, next to the code. It may be worth also reading How to make IPython notebook matplotlib plot inline for reference on how to use it in your code.

If you want interactivity as well, you can use the nbagg backend with %matplotlib notebook (in IPython 3.x), as described here.


回答 1

如果您正在运行IPython,它%matplotlib inline将使您的绘图输出出现并存储在笔记本中。

根据文件

要进行设置,matplotlib必须先执行%matplotlib magic command。这将执行必要的幕后设置,以使IPython能够与正确地并行工作matplotlib;但是,它实际上并不执行任何Python导入命令,也就是说,没有名称添加到命名空间。

由IPython提供的一个特别有趣的后端是 inline后端。此功能仅适用于Jupyter Notebook和Jupyter QtConsole。可以按以下方式调用它:

%matplotlib inline

使用此后端,绘图命令的输出将在Jupyter笔记本之类的前端内联显示,直接位于生成它的代码单元下方。然后,生成的图也将存储在笔记本文档中。

Provided you are running IPython, the %matplotlib inline will make your plot outputs appear and be stored within the notebook.

According to documentation

To set this up, before any plotting or import of matplotlib is performed you must execute the %matplotlib magic command. This performs the necessary behind-the-scenes setup for IPython to work correctly hand in hand with matplotlib; it does not, however, actually execute any Python import commands, that is, no names are added to the namespace.

A particularly interesting backend, provided by IPython, is the inline backend. This is available only for the Jupyter Notebook and the Jupyter QtConsole. It can be invoked as follows:

%matplotlib inline

With this backend, the output of plotting commands is displayed inline within frontends like the Jupyter notebook, directly below the code cell that produced it. The resulting plots will then also be stored in the notebook document.


回答 2

如果要将绘图添加到Jupyter笔记本,则%matplotlib inline是标准解决方案。还有其他魔术命令将matplotlib在Jupyter中交互使用。

%matplotlibplt现在任何绘图命令都将导致图形窗口打开,并且可以运行其他命令来更新绘图。某些更改不会自动绘制,以强制更新,使用plt.draw()

%matplotlib notebook:将导致交互式绘图嵌入到笔记本中,您可以缩放图形并调整其大小

%matplotlib inline:仅在笔记本中绘制静态图像

If you want to add plots to your Jupyter notebook, then %matplotlib inline is a standard solution. And there are other magic commands will use matplotlib interactively within Jupyter.

%matplotlib: any plt plot command will now cause a figure window to open, and further commands can be run to update the plot. Some changes will not draw automatically, to force an update, use plt.draw()

%matplotlib notebook: will lead to interactive plots embedded within the notebook, you can zoom and resize the figure

%matplotlib inline: only draw static images in the notebook


回答 3

从IPython 5.0和matplotlib 2.0开始,您可以避免使用IPython的特定魔术,而使用 matplotlib.pyplot.ion()/matplotlib.pyplot.ioff()具有在IPython之外工作的优点。

ipython文档

Starting with IPython 5.0 and matplotlib 2.0 you can avoid the use of IPython’s specific magic and use matplotlib.pyplot.ion()/matplotlib.pyplot.ioff() which have the advantages of working outside of IPython as well.

ipython docs


回答 4

如果您不知道后端是什么,可以阅读以下内容:https : //matplotlib.org/tutorials/introductory/usage.html#backends

有些人从python shell交互地使用matplotlib,并且在键入命令时弹出绘图窗口。有些人运行Jupyter笔记本并绘制内联图以进行快速数据分析。其他人则将matplotlib嵌入到wxpython或pygtk等图形用户界面中,以构建丰富的应用程序。有些人在批处理脚本中使用matplotlib从数值模拟生成后记图像,还有一些人运行Web应用程序服务器来动态提供图形。为了支持所有这些用例,matplotlib可以针对不同的输出,这些功能中的每一个都称为后端。“前端”是用户面对的代码,即绘图代码,而“后端”则是幕后的所有艰苦工作以制作图形。

因此,当您键入%matplotlib inline时,它将激活内联后端。如前几篇文章所述:

使用此后端,绘图命令的输出将在Jupyter笔记本之类的前端内联显示,直接位于生成它的代码单元下方。然后,生成的图也将存储在笔记本文档中。

If you don’t know what backend is , you can read this: https://matplotlib.org/tutorials/introductory/usage.html#backends

Some people use matplotlib interactively from the python shell and have plotting windows pop up when they type commands. Some people run Jupyter notebooks and draw inline plots for quick data analysis. Others embed matplotlib into graphical user interfaces like wxpython or pygtk to build rich applications. Some people use matplotlib in batch scripts to generate postscript images from numerical simulations, and still others run web application servers to dynamically serve up graphs. To support all of these use cases, matplotlib can target different outputs, and each of these capabilities is called a backend; the “frontend” is the user facing code, i.e., the plotting code, whereas the “backend” does all the hard work behind-the-scenes to make the figure.

So when you type %matplotlib inline , it activates the inline backend. As discussed in the previous posts :

With this backend, the output of plotting commands is displayed inline within frontends like the Jupyter notebook, directly below the code cell that produced it. The resulting plots will then also be stored in the notebook document.


回答 5

这只是意味着我们作为代码一部分创建的任何图形都将出现在同一笔记本中,而不是在单独的窗口中出现,如果我们不使用此魔术语句,则该窗口将发生。

It just means that any graph which we are creating as a part of our code will appear in the same notebook and not in separate window which would happen if we have not used this magic statement.


回答 6

解释清楚:

如果您不喜欢这样:

%matplotlib inline

然后在jupyter笔记本中保存它。

To explain it clear:

If you don’t like it like this:

add %matplotlib inline

and there you have it in your jupyter notebook.


回答 7

TL; DR

%matplotlib inline -显示输出内联


IPython内核具有通过执行代码来显示图的功能。IPython内核旨在与matplotlib绘图库无缝协作以提供此功能。

%matplotlib是一个魔术命令,它执行必要的幕后设置,以使IPython与IPython紧密配合matplotlib。它不执行任何Python导入命令,即没有名称添加到命名空间。

在单独的窗口中显示输出

%matplotlib

内联显示输出

(仅适用于Jupyter Notebook和Jupyter QtConsole)

%matplotlib inline

与交互式后端一起显示

(有效值'GTK3Agg', 'GTK3Cairo', 'MacOSX', 'nbAgg', 'Qt4Agg', 'Qt4Cairo', 'Qt5Agg', 'Qt5Cairo', 'TkAgg', 'TkCairo', 'WebAgg', 'WX', 'WXAgg', 'WXCairo', 'agg', 'cairo', 'pdf', 'pgf', 'ps', 'svg', 'template'

%matplotlib gtk

示例-GTK3Agg-对GTK 3.x画布的Agg渲染(需要PyGObject和pycairo或cairocffi)。

有关matplotlib交互式后端的更多详细信息:此处


与开始IPython 5.0matplotlib 2.0你能避免使用IPython中的特殊魔法和使用matplotlib.pyplot.ion()/ matplotlib.pyplot.ioff() 其中有工作的IPython之外还有优势。

参考:IPython丰富的输出-交互式绘图

TL;DR

%matplotlib inline – Displays output inline


IPython kernel has the ability to display plots by executing code. The IPython kernel is designed to work seamlessly with the matplotlib plotting library to provide this functionality.

%matplotlib is a magic command which performs the necessary behind-the-scenes setup for IPython to work correctly hand-in-hand with matplotlib; it does not execute any Python import commands, that is, no names are added to the namespace.

Display output in separate window

%matplotlib

Display output inline

(available only for the Jupyter Notebook and the Jupyter QtConsole)

%matplotlib inline

Display with interactive backends

(valid values 'GTK3Agg', 'GTK3Cairo', 'MacOSX', 'nbAgg', 'Qt4Agg', 'Qt4Cairo', 'Qt5Agg', 'Qt5Cairo', 'TkAgg', 'TkCairo', 'WebAgg', 'WX', 'WXAgg', 'WXCairo', 'agg', 'cairo', 'pdf', 'pgf', 'ps', 'svg', 'template')

%matplotlib gtk

Example – GTK3Agg – An Agg rendering to a GTK 3.x canvas (requires PyGObject and pycairo or cairocffi).

More details about matplotlib interactive backends: here


Starting with IPython 5.0 and matplotlib 2.0 you can avoid the use of IPython’s specific magic and use matplotlib.pyplot.ion()/matplotlib.pyplot.ioff() which have the advantages of working outside of IPython as well.

Refer: IPython Rich Output – Interactive Plotting


回答 8

如果您正在运行Jupyter Notebook,%matplotlib内联命令将使您的绘图输出出现在笔记本中,也可以存储。

Provided you are running Jupyter Notebook, the %matplotlib inline command will make your plot outputs appear in the notebook, also can be stored.


回答 9

不必写那个。没有(%matplotlib)魔术功能,对我来说效果很好。我正在使用Sypder编译器,这是Anaconda随附的。

It is not mandatory to write that. It worked fine for me without (%matplotlib) magic function. I am using Sypder compiler, one that comes with in Anaconda.


如何使IPython Notebook Matplotlib内联绘图

问题:如何使IPython Notebook Matplotlib内联绘图

我正在MacOS X上使用Python 2.7.2和IPython 1.1.0的情况下使用IPython Notebook。

我无法获得matplotlib图形来内联显示。

import matplotlib
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline  

我也试过了%pylab inline和ipython命令行参数,--pylab=inline但这没什么区别。

x = np.linspace(0, 3*np.pi, 500)
plt.plot(x, np.sin(x**2))
plt.title('A simple chirp')
plt.show()

我得到的不是内联图形,而是:

<matplotlib.figure.Figure at 0x110b9c450>

matplotlib.get_backend()表明我有'module://IPython.kernel.zmq.pylab.backend_inline'后端。

I am trying to use IPython notebook on MacOS X with Python 2.7.2 and IPython 1.1.0.

I cannot get matplotlib graphics to show up inline.

import matplotlib
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline  

I have also tried %pylab inline and the ipython command line arguments --pylab=inline but this makes no difference.

x = np.linspace(0, 3*np.pi, 500)
plt.plot(x, np.sin(x**2))
plt.title('A simple chirp')
plt.show()

Instead of inline graphics, I get this:

<matplotlib.figure.Figure at 0x110b9c450>

And matplotlib.get_backend() shows that I have the 'module://IPython.kernel.zmq.pylab.backend_inline' backend.


回答 0

%matplotlib inline在笔记本的第一个单元中使用了它,并且可以正常工作。我认为您应该尝试:

%matplotlib inline

import matplotlib
import numpy as np
import matplotlib.pyplot as plt

通过在配置文件中设置以下配置选项,默认情况下,您也始终可以始终默认以内联模式启动所有IPython内核:

c.IPKernelApp.matplotlib=<CaselessStrEnum>
  Default: None
  Choices: ['auto', 'gtk', 'gtk3', 'inline', 'nbagg', 'notebook', 'osx', 'qt', 'qt4', 'qt5', 'tk', 'wx']
  Configure matplotlib for interactive use with the default matplotlib backend.

I used %matplotlib inline in the first cell of the notebook and it works. I think you should try:

%matplotlib inline

import matplotlib
import numpy as np
import matplotlib.pyplot as plt

You can also always start all your IPython kernels in inline mode by default by setting the following config options in your config files:

c.IPKernelApp.matplotlib=<CaselessStrEnum>
  Default: None
  Choices: ['auto', 'gtk', 'gtk3', 'inline', 'nbagg', 'notebook', 'osx', 'qt', 'qt4', 'qt5', 'tk', 'wx']
  Configure matplotlib for interactive use with the default matplotlib backend.

回答 1

如果您的matplotlib版本高于1.4,则也可以使用

IPython 3.x及更高版本

%matplotlib notebook

import matplotlib.pyplot as plt

旧版本

%matplotlib nbagg

import matplotlib.pyplot as plt

两者都将激活nbagg后端,从而启用交互性。

If your matplotlib version is above 1.4, it is also possible to use

IPython 3.x and above

%matplotlib notebook

import matplotlib.pyplot as plt

older versions

%matplotlib nbagg

import matplotlib.pyplot as plt

Both will activate the nbagg backend, which enables interactivity.


回答 2

Ctrl + Enter

%matplotlib inline

魔线:D

请参阅:使用Matplotlib进行绘图

Ctrl + Enter

%matplotlib inline

Magic Line :D

See: Plotting with Matplotlib.


回答 3

使用%pylab inline魔术命令。

Use the %pylab inline magic command.


回答 4

要在Jupyter(IPython 3)中默认使matplotlib内联:

  1. 编辑档案 ~/.ipython/profile_default/ipython_config.py

  2. 加线 c.InteractiveShellApp.matplotlib = 'inline'

请注意,添加该行将ipython_notebook_config.py不起作用。否则,它可以与Jupyter和IPython 3.1.0一起使用

To make matplotlib inline by default in Jupyter (IPython 3):

  1. Edit file ~/.ipython/profile_default/ipython_config.py

  2. Add line c.InteractiveShellApp.matplotlib = 'inline'

Please note that adding this line to ipython_notebook_config.py would not work. Otherwise it works well with Jupyter and IPython 3.1.0


回答 5

我必须同意foobarbecue(我的建议不足,无法简单地在他的帖子下插入评论):

--pylab根据Fernando Perez(ipythonnb的创建者)的说法,现在建议不要使用该参数启动python笔记本。%matplotlib inline应该是笔记本的初始命令。

看到这里:http : //nbviewer.ipython.org/github/ipython/ipython/blob/1.x/examples/notebooks/Part%203%20-%20Plotting%20with%20Matplotlib.ipynb

I have to agree with foobarbecue (I don’t have enough recs to be able to simply insert a comment under his post):

It’s now recommended that python notebook isn’t started wit the argument --pylab, and according to Fernando Perez (creator of ipythonnb) %matplotlib inline should be the initial notebook command.

See here: http://nbviewer.ipython.org/github/ipython/ipython/blob/1.x/examples/notebooks/Part%203%20-%20Plotting%20with%20Matplotlib.ipynb


回答 6

我找到了一种非常令人满意的解决方法。我安装了Anaconda Python,现在对我来说开箱即用。

I found a workaround that is quite satisfactory. I installed Anaconda Python and this now works out of the box for me.


回答 7

我做了anaconda安装,但是matplotlib没有绘制

当我这样做时它开始绘图

import matplotlib
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline  

I did the anaconda install but matplotlib is not plotting

It starts plotting when i did this

import matplotlib
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline  

回答 8

您可以使用语法错误来模拟此问题,但是%matplotlib inline无法解决该问题。

首先是创建绘图的正确方法的示例。eNord9提供的导入内容和魔术可以使一切正常工作。

df_randNumbers1 = pd.DataFrame(np.random.randint(0,100,size=(100, 6)), columns=list('ABCDEF'))

df_randNumbers1.ix[:,["A","B"]].plot.kde()

但是,通过将()绘图类型的末尾保留为空白,您会收到含糊不清的非错误。

错误代码:

df_randNumbers1.ix[:,["A","B"]].plot.kde

错误示例:

<bound method FramePlotMethods.kde of <pandas.tools.plotting.FramePlotMethods object at 0x000001DDAF029588>>

除了这一行消息外,没有堆栈跟踪或其他明显的理由认为您犯了语法错误。该图不打印。

You can simulate this problem with a syntax mistake, however, %matplotlib inline won’t resolve the issue.

First an example of the right way to create a plot. Everything works as expected with the imports and magic that eNord9 supplied.

df_randNumbers1 = pd.DataFrame(np.random.randint(0,100,size=(100, 6)), columns=list('ABCDEF'))

df_randNumbers1.ix[:,["A","B"]].plot.kde()

However, by leaving the () off the end of the plot type you receive a somewhat ambiguous non-error.

Erronious code:

df_randNumbers1.ix[:,["A","B"]].plot.kde

Example error:

<bound method FramePlotMethods.kde of <pandas.tools.plotting.FramePlotMethods object at 0x000001DDAF029588>>

Other than this one line message, there is no stack trace or other obvious reason to think you made a syntax error. The plot doesn’t print.


回答 9

在Jupyter的单独单元中运行绘图命令时,我遇到了同样的问题:

In [1]:  %matplotlib inline
         import matplotlib
         import matplotlib.pyplot as plt
         import numpy as np
In [2]:  x = np.array([1, 3, 4])
         y = np.array([1, 5, 3])
In [3]:  fig = plt.figure()
         <Figure size 432x288 with 0 Axes>                      #this might be the problem
In [4]:  ax = fig.add_subplot(1, 1, 1)
In [5]:  ax.scatter(x, y)
Out[5]:  <matplotlib.collections.PathCollection at 0x12341234>  # CAN'T SEE ANY PLOT :(
In [6]:  plt.show()                                             # STILL CAN'T SEE IT :(

通过将绘图命令合并到单个单元格中解决了该问题:

In [1]:  %matplotlib inline
         import matplotlib
         import matplotlib.pyplot as plt
         import numpy as np
In [2]:  x = np.array([1, 3, 4])
         y = np.array([1, 5, 3])
In [3]:  fig = plt.figure()
         ax = fig.add_subplot(1, 1, 1)
         ax.scatter(x, y)
Out[3]:  <matplotlib.collections.PathCollection at 0x12341234>
         # AND HERE APPEARS THE PLOT AS DESIRED :)

I had the same problem when I was running the plotting commands in separate cells in Jupyter:

In [1]:  %matplotlib inline
         import matplotlib
         import matplotlib.pyplot as plt
         import numpy as np
In [2]:  x = np.array([1, 3, 4])
         y = np.array([1, 5, 3])
In [3]:  fig = plt.figure()
         <Figure size 432x288 with 0 Axes>                      #this might be the problem
In [4]:  ax = fig.add_subplot(1, 1, 1)
In [5]:  ax.scatter(x, y)
Out[5]:  <matplotlib.collections.PathCollection at 0x12341234>  # CAN'T SEE ANY PLOT :(
In [6]:  plt.show()                                             # STILL CAN'T SEE IT :(

The problem was solved by merging the plotting commands into a single cell:

In [1]:  %matplotlib inline
         import matplotlib
         import matplotlib.pyplot as plt
         import numpy as np
In [2]:  x = np.array([1, 3, 4])
         y = np.array([1, 5, 3])
In [3]:  fig = plt.figure()
         ax = fig.add_subplot(1, 1, 1)
         ax.scatter(x, y)
Out[3]:  <matplotlib.collections.PathCollection at 0x12341234>
         # AND HERE APPEARS THE PLOT AS DESIRED :)

pip和conda有什么区别?

问题:pip和conda有什么区别?

我知道pip是python软件包的软件包管理器。但是,我看到IPython网站conda上的安装用于安装IPython。

我可以pip用来安装IPython吗?conda我已经拥有了为什么还要用作另一个python软件包管理器pip

pip和之间有什么区别conda

I know pip is a package manager for python packages. However, I saw the installation on IPython’s website use conda to install IPython.

Can I use pip to install IPython? Why should I use conda as another python package manager when I already have pip?

What is the difference between pip and conda?


回答 0

引用来自Conda博客

参与python世界已经很长时间了,我们都知道pip,easy_install和virtualenv,但是这些工具不能满足我们所有的特定要求。主要问题是它们专注于Python,而忽略了非Python库依赖项,例如HDF5,MKL,LLVM等,它们的源代码中没有setup.py,也没有将文件安装到Python的站点中-packages目录。

因此,Conda是一种包装工具和安装程序,旨在做更多的事情pip。处理Python包之外的库依赖关系以及Python包本身。Conda也像创建虚拟环境一样virtualenv

因此,也许应该将Conda与Buildout进行比较,后者是另一个可以让您处理Python和非Python安装任务的工具。

由于Conda引入了新的包装格式,因此您不能pip与Conda互换使用。 pip无法安装Conda软件包格式。您可以使用并排的两个工具侧(通过安装pipconda install pip),但他们不具备互操作性无论是。

自编写此答案以来,Anaconda 理解Conda和Pip发布了新页面,该页面也与此相呼应:

这凸显了conda和pip之间的关键区别。Pip安装Python软件包,而conda安装软件包,其中可能包含以任何语言编写的软件。例如,在使用pip之前,必须通过系统软件包管理器或下载并运行安装程序来安装Python解释器。另一方面,Conda可以直接安装Python软件包以及Python解释器。

并进一步

有时需要一个软件包,该软件包不是conda软件包,但在PyPI上可用,可以与pip一起安装。在这些情况下,尝试同时使用conda和pip是有意义的。

Quoting from the Conda blog:

Having been involved in the python world for so long, we are all aware of pip, easy_install, and virtualenv, but these tools did not meet all of our specific requirements. The main problem is that they are focused around Python, neglecting non-Python library dependencies, such as HDF5, MKL, LLVM, etc., which do not have a setup.py in their source code and also do not install files into Python’s site-packages directory.

So Conda is a packaging tool and installer that aims to do more than what pip does; handle library dependencies outside of the Python packages as well as the Python packages themselves. Conda also creates a virtual environment, like virtualenv does.

As such, Conda should be compared to Buildout perhaps, another tool that lets you handle both Python and non-Python installation tasks.

Because Conda introduces a new packaging format, you cannot use pip and Conda interchangeably; pip cannot install the Conda package format. You can use the two tools side by side (by installing pip with conda install pip) but they do not interoperate either.

Since writing this answer, Anaconda has published a new page on Understanding Conda and Pip, which echoes this as well:

This highlights a key difference between conda and pip. Pip installs Python packages whereas conda installs packages which may contain software written in any language. For example, before using pip, a Python interpreter must be installed via a system package manager or by downloading and running an installer. Conda on the other hand can install Python packages as well as the Python interpreter directly.

and further on

Occasionally a package is needed which is not available as a conda package but is available on PyPI and can be installed with pip. In these cases, it makes sense to try to use both conda and pip.


回答 1

这是一个简短的摘要:

点子

  • 仅Python软件包。
  • 从源代码编译所有内容。编辑:pip现在会安装二进制车轮(如果可用)。
  • 受核心Python社区的祝福(即Python 3.4+包含自动引导pip的代码)。

康达

  • 不可知的Python。现有软件包的主要焦点是用于Python,的确Conda本身是用Python编写的,但是您也可以拥有用于C库,R软件包或其他任何东西的Conda软件包。
  • 安装二进制文件。有一个名为的工具conda build可以从源代码构建软件包,但conda install它本身可以从已构建的Conda软件包安装东西。
  • 外部。Conda是Anaconda的软件包管理器,它是Continuum Analytics提供的Python发行版,但也可以在Anaconda之外使用。您可以通过pip安装将其与现有的Python安装配合使用(尽管除非您有充分的理由使用现有的安装,否则不建议这样做)。

在两种情况下:

  • 用Python编写
  • 开源(Conda是BSD,pip是MIT)

实际上,Conda的前两个要点是使许多包装优于点子的原因。由于pip是从源代码安装的,因此如果您无法编译源代码,则可能会很麻烦地安装东西(在Windows上尤其如此,但在Linux上,如果软件包中包含一些困难的C或FORTRAN库,甚至可能也是这样。依赖项)。Conda从二进制安装,这意味着某人(例如Continuum)已经完成了编译软件包的艰苦工作,因此安装很容易。

如果您对构建自己的软件包感兴趣,也有一些区别。例如,pip是建立在setuptools之上的,而Conda使用自己的格式,这种格式具有一些优点(例如,静态的,Python不可知的)。

Here is a short rundown:

pip

  • Python packages only.
  • Compiles everything from source. EDIT: pip now installs binary wheels, if they are available.
  • Blessed by the core Python community (i.e., Python 3.4+ includes code that automatically bootstraps pip).

conda

  • Python agnostic. The main focus of existing packages are for Python, and indeed Conda itself is written in Python, but you can also have Conda packages for C libraries, or R packages, or really anything.
  • Installs binaries. There is a tool called conda build that builds packages from source, but conda install itself installs things from already built Conda packages.
  • External. Conda is the package manager of Anaconda, the Python distribution provided by Continuum Analytics, but it can be used outside of Anaconda too. You can use it with an existing Python installation by pip installing it (though this is not recommended unless you have a good reason to use an existing installation).

In both cases:

  • Written in Python
  • Open source (Conda is BSD and pip is MIT)

The first two bullet points of Conda are really what make it advantageous over pip for many packages. Since pip installs from source, it can be painful to install things with it if you are unable to compile the source code (this is especially true on Windows, but it can even be true on Linux if the packages have some difficult C or FORTRAN library dependencies). Conda installs from binary, meaning that someone (e.g., Continuum) has already done the hard work of compiling the package, and so the installation is easy.

There are also some differences if you are interested in building your own packages. For instance, pip is built on top of setuptools, whereas Conda uses its own format, which has some advantages (like being static, and again, Python agnostic).


回答 2

其他答案对这些细节给出了合理的描述,但我想强调一些高级要点。

pip是一个软件包管理器,可简化python软件包的安装,升级和卸载。它还适用于虚拟python环境。

conda是任何软件(安装,升级和卸载)的软件包管理器。它还适用于虚拟系统环境。

conda设计的目标之一是促进用户所需的整个软件堆栈的软件包管理,其中一个或多个python版本可能只是其中的一小部分。这包括低级库(例如线性代数),编译器(例如Windows上的mingw),编辑器,版本控制工具(例如Hg和Git)或其他需要分发和管理的内容

对于版本管理,pip允许您在多个python环境之间切换和管理。

Conda允许您在多个通用环境之间进行切换和管理,在多个通用环境中,其他多个版本的版本号可能会有所不同,例如C库,编译器,测试套件或数据库引擎等。

Conda不是以Windows为中心的,但是在Windows上,当需要安装和管理需要编译的复杂科学软件包时,它是目前可用的高级解决方案。

当我想到尝试通过Windows上的pip编译许多这些软件包或pip install在需要编译时调试失败的会话时浪费了多少时间时,我想哭。

最后,Continuum Analytics还托管(免费)binstar.org(现在称为anaconda.org),以允许常规软件包开发人员创建自己的自定义(内置!)软件堆栈,包用户可以conda install从中使用它们。

The other answers give a fair description of the details, but I want to highlight some high-level points.

pip is a package manager that facilitates installation, upgrade, and uninstallation of python packages. It also works with virtual python environments.

conda is a package manager for any software (installation, upgrade and uninstallation). It also works with virtual system environments.

One of the goals with the design of conda is to facilitate package management for the entire software stack required by users, of which one or more python versions may only be a small part. This includes low-level libraries, such as linear algebra, compilers, such as mingw on Windows, editors, version control tools like Hg and Git, or whatever else requires distribution and management.

For version management, pip allows you to switch between and manage multiple python environments.

Conda allows you to switch between and manage multiple general purpose environments across which multiple other things can vary in version number, like C-libraries, or compilers, or test-suites, or database engines and so on.

Conda is not Windows-centric, but on Windows it is by far the superior solution currently available when complex scientific packages requiring compilation are required to be installed and managed.

I want to weep when I think of how much time I have lost trying to compile many of these packages via pip on Windows, or debug failed pip install sessions when compilation was required.

As a final point, Continuum Analytics also hosts (free) binstar.org (now called anaconda.org) to allow regular package developers to create their own custom (built!) software stacks that their package-users will be able to conda install from.


回答 3

不要再让您感到困惑了,但是您也可以在conda环境中使用pip,这可以验证上面的一般管理员和python特定管理员的评论。

conda install -n testenv pip
source activate testenv
pip <pip command>

您还可以将pip添加到任何环境的默认程序包中,因此每次都会显示pip,因此您不必遵循上述代码段。

Not to confuse you further, but you can also use pip within your conda environment, which validates the general vs. python specific managers comments above.

conda install -n testenv pip
source activate testenv
pip <pip command>

you can also add pip to default packages of any environment so it is present each time so you don’t have to follow the above snippet.


回答 4

引用康达在Continuum网站上发表的关于数据科学的文章:

康达vs点

Python程序员可能很熟悉pip从PyPI下载软件包并管理他们的要求。尽管conda和pip都是程序包管理器,但它们却大不相同:

  • Pip是特定于Python软件包的,而conda是与语言无关的,这意味着我们可以使用conda管理任何语言的软件包。
  • Conda本机创建与语言无关的环境,而pip依靠virtualenv仅管理Python环境尽管建议始终使用conda软件包,但conda也包含pip,因此您不必在这两者之间进行选择。例如,要安装没有conda软件包但可通过pip获得的python软件包,请运行,例如:
conda install pip
pip install gensim

Quote from Conda for Data Science article onto Continuum’s website:

Conda vs pip

Python programmers are probably familiar with pip to download packages from PyPI and manage their requirements. Although, both conda and pip are package managers, they are very different:

  • Pip is specific for Python packages and conda is language-agnostic, which means we can use conda to manage packages from any language Pip compiles from source and conda installs binaries, removing the burden of compilation
  • Conda creates language-agnostic environments natively whereas pip relies on virtualenv to manage only Python environments Though it is recommended to always use conda packages, conda also includes pip, so you don’t have to choose between the two. For example, to install a python package that does not have a conda package, but is available through pip, just run, for example:
conda install pip
pip install gensim

回答 5

引用《Conda:神话与误解》(全面描述):

误解3:Conda和Pip是直接竞争对手

现实:Conda和pip服务于不同的目的,仅直接竞争一小部分任务:即在隔离的环境中安装Python软件包。

皮普,代表P IP nstalls P ackages,是Python的官方认可的包管理器,并且是最常用的在其上安装Python包索引(PyPI中)发布的数据包。pip和PyPI均受Python Packaging Authority(PyPA)管辖和支持。

简而言之,pip是Python软件包的通用管理器。conda是与语言无关的跨平台环境管理器。对于用户而言,最明显的区别可能是:pip在任何环境中安装python软件包;conda在conda环境中安装任何软件包。如果您要做的只是在隔离的环境中安装Python软件包,则conda和pip + virtualenv通常是可互换的,从而在依赖项处理和软件包可用性方面取得了一些差异。隔离环境是指conda-env或virtualenv,您可以在其中安装软件包而无需修改系统Python安装。

即使抛开神话#2,如果我们只关注Python软件包的安装,conda和pip也可以为不同的受众和不同的目的服务。例如,如果要管理现有系统Python安装中的Python软件包,conda不能为您提供帮助:根据设计,它只能在conda环境中安装软件包。例如,如果您想使用许多依赖于外部依赖关系的Python包(NumPy,SciPy和Matplotlib是常见的示例),而以有意义的方式跟踪这些依赖关系时,pip并不能帮助您:通过设计,它仅管理Python软件包。

Conda和pip不是竞争对手,而是针对不同用户群和使用方式的工具。

Quoting from Conda: Myths and Misconceptions (a comprehensive description):

Myth #3: Conda and pip are direct competitors

Reality: Conda and pip serve different purposes, and only directly compete in a small subset of tasks: namely installing Python packages in isolated environments.

Pip, which stands for Pip Installs Packages, is Python’s officially-sanctioned package manager, and is most commonly used to install packages published on the Python Package Index (PyPI). Both pip and PyPI are governed and supported by the Python Packaging Authority (PyPA).

In short, pip is a general-purpose manager for Python packages; conda is a language-agnostic cross-platform environment manager. For the user, the most salient distinction is probably this: pip installs python packages within any environment; conda installs any package within conda environments. If all you are doing is installing Python packages within an isolated environment, conda and pip+virtualenv are mostly interchangeable, modulo some difference in dependency handling and package availability. By isolated environment I mean a conda-env or virtualenv, in which you can install packages without modifying your system Python installation.

Even setting aside Myth #2, if we focus on just installation of Python packages, conda and pip serve different audiences and different purposes. If you want to, say, manage Python packages within an existing system Python installation, conda can’t help you: by design, it can only install packages within conda environments. If you want to, say, work with the many Python packages which rely on external dependencies (NumPy, SciPy, and Matplotlib are common examples), while tracking those dependencies in a meaningful way, pip can’t help you: by design, it manages Python packages and only Python packages.

Conda and pip are not competitors, but rather tools focused on different groups of users and patterns of use.


回答 6

对于WINDOWS用户

最近,“标准”包装工具的状况正在改善:

  • 截至9月,在pypi本身上,有48%的车轮包装。2015年11月11日(高于2015年5月的38%和2014年9月的24%),

  • 现在,最新的python 2.7.9支持开箱即用的wheel格式,

“标准” +“调整”包装工具的状况也在改善:

  • 您可以在http://www.lfd.uci.edu/~gohlke/pythonlibs上找到几乎所有关于转轮格式的科学软件包,

  • mingwpy项目可能有一天为Windows用户带来一个“编译”包,允许在需要时从源代码安装所有内容。

“康达”包装对于所服务的市场而言仍然更好,并强调了“标准” 应该改进的地方。

(同样,在标准车轮系统和conda系统中,或者在扩展方面,依赖规范的多方面努力不是很Python,如果所有这些打包的“核心”技术都可以通过某种PEP收敛,那就太好了)

For WINDOWS users

“standard” packaging tools situation is improving recently:

  • on pypi itself, there are now 48% of wheel packages as of sept. 11th 2015 (up from 38% in may 2015 , 24% in sept. 2014),

  • the wheel format is now supported out-of-the-box per latest python 2.7.9,

“standard”+”tweaks” packaging tools situation is improving also:

  • you can find nearly all scientific packages on wheel format at http://www.lfd.uci.edu/~gohlke/pythonlibs,

  • the mingwpy project may bring one day a ‘compilation’ package to windows users, allowing to install everything from source when needed.

“Conda” packaging remains better for the market it serves, and highlights areas where the “standard” should improve.

(also, the dependency specification multiple-effort, in standard wheel system and in conda system, or buildout, is not very pythonic, it would be nice if all these packaging ‘core’ techniques could converge, via a sort of PEP)


回答 7

pip 是包裹经理。

conda 既是包管理器又是环境管理器。

详情:

参考文献

pip is a package manager.

conda is both a package manager and an environment manager.

Detail:

References


回答 8

我可以使用pip安装iPython吗?

当然,两者(第一种方法在页面上)

pip install ipython

和(第三种方法,第二种是conda

您可以从GitHub或PyPI手动下载IPython。要安装这些版本之一,请解压缩它并使用终端从顶级源目录运行以下命令:

pip install .

官方推荐的安装方法

当我已经有了pip时,为什么还要使用conda作为另一个python软件包管理器?

这里所说:

如果您需要一个特定的软件包,也许仅用于一个项目,或者需要与其他人共享该项目,那么conda似乎更合适。

康达(YMMV)超过点

  • 使用非Python工具的项目
  • 与同事分享
  • 在版本之间切换
  • 在具有不同库版本的项目之间切换

pip和conda有什么区别?

其他所有人对此都有广泛的回答。

Can I use pip to install iPython?

Sure, both (first approach on page)

pip install ipython

and (third approach, second is conda)

You can manually download IPython from GitHub or PyPI. To install one of these versions, unpack it and run the following from the top-level source directory using the Terminal:

pip install .

are officially recommended ways to install.

Why should I use conda as another python package manager when I already have pip?

As said here:

If you need a specific package, maybe only for one project, or if you need to share the project with someone else, conda seems more appropriate.

Conda surpasses pip in (YMMV)

  • projects that use non-python tools
  • sharing with colleagues
  • switching between versions
  • switching between projects with different library versions

What is the difference between pip and conda?

That is extensively answered by everyone else.


回答 9

pip 仅适用于Python

conda仅适用于Anaconda +其他科学软件包,例如R依赖等。并非每个人都需要Python附带的Anaconda。Anaconda主要适合那些进行机器学习/深度学习等的人。Casual Python开发人员不会在他的笔记本电脑上运行Anaconda。

pip is for Python only

conda is only for Anaconda + other scientific packages like R dependencies etc. NOT everyone needs Anaconda that already comes with Python. Anaconda is mostly for those who do Machine learning/deep learning etc. Casual Python dev won’t run Anaconda on his laptop.


回答 10

我可能已经发现了另一小的区别。我在python环境下/usr而不是在/home任何环境下。为了安装它,我将不得不使用sudo install pip。对我来说,不想要的副作用sudo install pip是比被广泛报道的其他地方略有不同:这样做之后,我还得跑pythonsudo以进口任何的sudo-installed包。我放弃了这一点,最终发现我可以sudo conda将软件包安装到一个环境中/usr,然后在该环境下可以正常导入而不需要sudo获得许可python。我什sudo conda至习惯于修复损坏的东西,pip而不是使用sudo pip uninstall pipor sudo pip --upgrade install pip

I may have found one further difference of a minor nature. I have my python environments under /usr rather than /home or whatever. In order to install to it, I would have to use sudo install pip. For me, the undesired side effect of sudo install pip was slightly different than what are widely reported elsewhere: after doing so, I had to run python with sudo in order to import any of the sudo-installed packages. I gave up on that and eventually found I could use sudo conda to install packages to an environment under /usr which then imported normally without needing sudo permission for python. I even used sudo conda to fix a broken pip rather than using sudo pip uninstall pip or sudo pip --upgrade install pip.


IPython 官方存储库 包含网站、文档构建等内容

IPython:高效交互计算

概述

欢迎来到IPython。有关我们的完整文档,请访问ipython.readthedocs.io并包含有关如何安装、使用和参与项目的信息。IPython(交互式Python)是用于多种编程语言交互计算的命令shell,最初是为Python编程语言开发的,它提供自检、富媒体、shell语法、制表符完成和历史记录

IPython版本和Python支持

从IPython 7.10开始,IPython紧随其后NEP 29

IPython 7.17+需要Python版本3.7及更高版本

IPython 7.10+需要Python 3.6版和更高版本

IPython 7.0需要Python 3.5版和更高版本

IPython 6.x需要Python 3.3版和更高版本

IPython 5.x LTS是与Python2.7兼容的版本。如果您需要Python 2支持,您可以必须使用IPython 5.x LTS。请根据需要更新您的项目配置和要求

笔记本、Qt控制台和许多其他部件现在是朱庇特请参阅Jupyter installation docs如果你想用这些

IPython的主要功能

全面的对象自省

输入历史记录,跨会话持久

在具有自动生成的引用的会话期间缓存输出结果

可扩展的制表符完成,默认情况下支持完成python变量和关键字、文件名和函数关键字

可扩展的“魔术”命令系统,用于控制环境并执行许多与IPython或操作系统相关的任务

丰富的配置系统,可在不同设置之间轻松切换(比每次更改$PYTHONSTARTUP环境变量更简单)

会话记录和重载

用于特殊目的情况的可扩展语法处理

访问具有用户可扩展别名system的系统外壳

可轻松嵌入到其他Python程序和GUI中

对PDB调试器和Python探查器的集成访问

开发与即时运行

您可以在上找到最新版本的开发文档readthedocs

通过在终端键入以下命令,甚至无需在系统范围内安装IPython,即可从该目录运行IPython:

$ python -m IPython

或查看development installation docs有关最新版本的信息,请阅读文档

旧版本IPython的文档和安装说明可在IPython website

IPython需要Python版本3或更高版本

从版本6.0开始,IPython不支持Python 2.7、3.0、3.1或3.2

要获得与Python 2.7兼容的版本,请安装5.x LTS长期支持版本

如果您遇到此错误消息,您可能正在尝试从源代码安装或使用IPython。您需要检查远程5.x分支机构。如果您使用的是GIT,则应该可以执行以下操作:

$ git fetch origin
$ git checkout 5.x

如果您在常规安装IPython时遇到此错误消息,则可能需要更新包管理器,例如,如果您使用的是pip,请使用以下命令检查pip的版本:

$ pip --version

您需要将pip更新到9.0.1版或更高版本。如果您使用的不是pip,请向软件包的维护人员咨询您的软件包管理器。

有关更多信息,请参阅我们的博客帖子之一:

https://blog.jupyter.org/release-of-ipython-5-0-8ce60b8d2e8e

以及以下拉式请求以供讨论:

https://github.com/ipython/ipython/pull/9900

如果您正在调用setup.py直接-这是您不应该使用的-使用或正在使用easy_install如果是这种情况,请使用pip
install .
而不是setup.py install,以及pip install -e .而不是setup.py develop如果您依赖IPython作为依赖项,则可能还希望对IPython具有条件依赖项,具体取决于Python版本:

install_req = ['ipython']
if sys.version_info[0] < 3 and 'bdist_wheel' not in sys.argv:
    install_req.remove('ipython')
    install_req.append('ipython<6')

setup(
    ...
    install_requires=install_req
)

IPython的替代方案

IPython可能不合您的口味;如果是这样,您可能想要使用类似的项目:

忽略带有git故障的提交。忽略reRevsFile

从GIT 2.23开始,可以在不中断的情况下进行格式更改git blame请参阅git documentation有关更多详细信息,请参阅

要使用此功能,您必须:

  • 安装Git>=2.23
  • 通过运行以下命令配置您的本地GIT存储库:
    • POSIX:tools\configure-git-blame-ignore-revs.sh
    • 窗口:tools\configure-git-blame-ignore-revs.bat