标签归档:jupyter

从IPython Notebook中的日志记录模块获取输出

问题:从IPython Notebook中的日志记录模块获取输出

当我在IPython Notebook中运行以下命令时,看不到任何输出:

import logging
logging.basicConfig(level=logging.DEBUG)
logging.debug("test")

有人知道怎么做,这样我才能在笔记本中看到“测试”消息吗?

When I running the following inside IPython Notebook I don’t see any output:

import logging
logging.basicConfig(level=logging.DEBUG)
logging.debug("test")

Anyone know how to make it so I can see the “test” message inside the notebook?


回答 0

请尝试以下操作:

import logging
logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
logging.debug("test")

根据logging.basicConfig

通过创建带有默认Formatter的StreamHandler并将其添加到根记录器,对记录系统进行基本配置。如果没有为根记录器定义处理程序,则debug(),info(),warning(),error()和critical()函数将自动调用basicConfig()。

如果根记录器已经为其配置了处理程序,则此功能不执行任何操作。

似乎ipython笔记本在某处调用basicConfig(或设置处理程序)。

Try following:

import logging
logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
logging.debug("test")

According to logging.basicConfig:

Does basic configuration for the logging system by creating a StreamHandler with a default Formatter and adding it to the root logger. The functions debug(), info(), warning(), error() and critical() will call basicConfig() automatically if no handlers are defined for the root logger.

This function does nothing if the root logger already has handlers configured for it.

It seems like ipython notebook call basicConfig (or set handler) somewhere.


回答 1

如果仍要使用basicConfig,请像这样重新加载日志记录模块

from importlib import reload  # Not needed in Python 2
import logging
reload(logging)
logging.basicConfig(format='%(asctime)s %(levelname)s:%(message)s', level=logging.DEBUG, datefmt='%I:%M:%S')

If you still want to use basicConfig, reload the logging module like this

from importlib import reload  # Not needed in Python 2
import logging
reload(logging)
logging.basicConfig(format='%(asctime)s %(levelname)s:%(message)s', level=logging.DEBUG, datefmt='%I:%M:%S')

回答 2

我的理解是IPython会话开始记录日志,因此basicConfig不起作用。这是对我有用的设置(我希望这看起来不太好,因为我想将其用于几乎所有笔记本电脑):

import logging
logger = logging.getLogger()
fhandler = logging.FileHandler(filename='mylog.log', mode='a')
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
fhandler.setFormatter(formatter)
logger.addHandler(fhandler)
logger.setLevel(logging.DEBUG)

现在,当我运行时:

logging.error('hello!')
logging.debug('This is a debug message')
logging.info('this is an info message')
logging.warning('tbllalfhldfhd, warning.')

我在与笔记本相同的目录中得到一个“ mylog.log”文件,其中包含:

2015-01-28 09:49:25,026 - root - ERROR - hello!
2015-01-28 09:49:25,028 - root - DEBUG - This is a debug message
2015-01-28 09:49:25,029 - root - INFO - this is an info message
2015-01-28 09:49:25,032 - root - WARNING - tbllalfhldfhd, warning.

请注意,如果您在不重新启动IPython会话的情况下重新运行它,则会将重复的条目写入文件,因为现在将定义两个文件处理程序

My understanding is that the IPython session starts up logging so basicConfig doesn’t work. Here is the setup that works for me (I wish this was not so gross looking since I want to use it for almost all my notebooks):

import logging
logger = logging.getLogger()
fhandler = logging.FileHandler(filename='mylog.log', mode='a')
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
fhandler.setFormatter(formatter)
logger.addHandler(fhandler)
logger.setLevel(logging.DEBUG)

Now when I run:

logging.error('hello!')
logging.debug('This is a debug message')
logging.info('this is an info message')
logging.warning('tbllalfhldfhd, warning.')

I get a “mylog.log” file in the same directory as my notebook that contains:

2015-01-28 09:49:25,026 - root - ERROR - hello!
2015-01-28 09:49:25,028 - root - DEBUG - This is a debug message
2015-01-28 09:49:25,029 - root - INFO - this is an info message
2015-01-28 09:49:25,032 - root - WARNING - tbllalfhldfhd, warning.

Note that if you rerun this without restarting the IPython session it will write duplicate entries to the file since there would now be two file handlers defined


回答 3

请记住,stderr是logging模块的默认流,因此在IPython和Jupyter笔记本中,除非将流配置为stdout,否则可能看不到任何内容:

import logging
import sys

logging.basicConfig(format='%(asctime)s | %(levelname)s : %(message)s',
                     level=logging.INFO, stream=sys.stdout)

logging.info('Hello world!')

Bear in mind that stderr is the default stream for the logging module, so in IPython and Jupyter notebooks you might not see anything unless you configure the stream to stdout:

import logging
import sys

logging.basicConfig(format='%(asctime)s | %(levelname)s : %(message)s',
                     level=logging.INFO, stream=sys.stdout)

logging.info('Hello world!')

回答 4

现在对我有用的(Jupyter,笔记本服务器是:5.4.1,IPython 7.0.1)

import logging
logging.basicConfig()
logger = logging.getLogger('Something')
logger.setLevel(logging.DEBUG)

现在,我可以使用记录器来打印信息,否则,我只会看到默认级别(logging.WARNING)或更高级别的消息。

What worked for me now (Jupyter, notebook server is: 5.4.1, IPython 7.0.1)

import logging
logging.basicConfig()
logger = logging.getLogger('Something')
logger.setLevel(logging.DEBUG)

Now I can use logger to print info, otherwise I would see only message from the default level (logging.WARNING) or above.


回答 5

您可以通过运行配置日志记录 %config Application.log_level="INFO"

有关更多信息,请参见IPython内核选项。

You can configure logging by running %config Application.log_level="INFO"

For more information, see IPython kernel options


回答 6

我为这两个文件都设置了一个记录器,我希望它能显示在笔记本上。事实证明,添加文件处理程序会清除默认的流处理程序。

logger = logging.getLogger()

formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')

# Setup file handler
fhandler  = logging.FileHandler('my.log')
fhandler.setLevel(logging.DEBUG)
fhandler.setFormatter(formatter)

# Configure stream handler for the cells
chandler = logging.StreamHandler()
chandler.setLevel(logging.DEBUG)
chandler.setFormatter(formatter)

# Add both handlers
logger.addHandler(fhandler)
logger.addHandler(chandler)
logger.setLevel(logging.DEBUG)

# Show the handlers
logger.handlers

# Log Something
logger.info("Test info")
logger.debug("Test debug")
logger.error("Test error")

I setup a logger for both file and I wanted it to show up on the notebook. Turns out adding a filehandler clears out the default stream handlder.

logger = logging.getLogger()

formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')

# Setup file handler
fhandler  = logging.FileHandler('my.log')
fhandler.setLevel(logging.DEBUG)
fhandler.setFormatter(formatter)

# Configure stream handler for the cells
chandler = logging.StreamHandler()
chandler.setLevel(logging.DEBUG)
chandler.setFormatter(formatter)

# Add both handlers
logger.addHandler(fhandler)
logger.addHandler(chandler)
logger.setLevel(logging.DEBUG)

# Show the handlers
logger.handlers

# Log Something
logger.info("Test info")
logger.debug("Test debug")
logger.error("Test error")

回答 7

似乎适用于ipython / jupyter早期版本的解决方案不再起作用。

这是适用于ipython 7.9.0的有效解决方案(也已通过jupyter服务器6.0.2测试):

import logging
logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
logging.debug("test message")

DEBUG:root:test message

It seems that solutions that worked for older versions of ipython/jupyter no longer work.

Here is a working solution for ipython 7.9.0 (also tested with jupyter server 6.0.2):

import logging
logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
logging.debug("test message")

DEBUG:root:test message

我可以在GPU上运行Keras模型吗?

问题:我可以在GPU上运行Keras模型吗?

我正在运行Keras模型,提交截止日期为36小时,如果我在cpu上训练我的模型大约需要50个小时,是否可以在gpu上运行Keras?

我正在使用Tensorflow后端,并在未安装anaconda的Jupyter笔记本上运行它。

I’m running a Keras model, with a submission deadline of 36 hours, if I train my model on the cpu it will take approx 50 hours, is there a way to run Keras on gpu?

I’m using Tensorflow backend and running it on my Jupyter notebook, without anaconda installed.


回答 0

是的,您可以在GPU上运行keras模型。几件事您将必须首先检查。

  1. 您的系统具有GPU(Nvidia。因为AMD尚未运行)
  2. 您已经安装了Tensorflow的GPU版本
  3. 您已安装CUDA 安装说明
  4. 验证Tensorflow是否与GPU一起运行,检查GPU是否正常工作

sess = tf.Session(config=tf.ConfigProto(log_device_placement=True))

要么

from tensorflow.python.client import device_lib
print(device_lib.list_local_devices())

输出将是这样的:

[
  name: "/cpu:0"device_type: "CPU",
  name: "/gpu:0"device_type: "GPU"
]

完成所有这些操作后,您的模型将在GPU上运行:

要检查keras(> = 2.1.1)是否使用GPU:

from keras import backend as K
K.tensorflow_backend._get_available_gpus()

祝一切顺利。

Yes you can run keras models on GPU. Few things you will have to check first.

  1. your system has GPU (Nvidia. As AMD doesn’t work yet)
  2. You have installed the GPU version of tensorflow
  3. You have installed CUDA installation instructions
  4. Verify that tensorflow is running with GPU check if GPU is working

sess = tf.Session(config=tf.ConfigProto(log_device_placement=True))

OR

from tensorflow.python.client import device_lib
print(device_lib.list_local_devices())

output will be something like this:

[
  name: "/cpu:0"device_type: "CPU",
  name: "/gpu:0"device_type: "GPU"
]

Once all this is done your model will run on GPU:

To Check if keras(>=2.1.1) is using GPU:

from keras import backend as K
K.tensorflow_backend._get_available_gpus()

All the best.


回答 1

当然。我想您已经安装了TensorFlow for GPU。

导入keras后,需要添加以下块。我正在使用具有56核心cpu和gpu的计算机。

import keras
import tensorflow as tf


config = tf.ConfigProto( device_count = {'GPU': 1 , 'CPU': 56} ) 
sess = tf.Session(config=config) 
keras.backend.set_session(sess)

当然,这种用法会强制执行我的计算机的最大限制。您可以减少cpu和gpu消耗值。

Sure. I suppose that you have already installed TensorFlow for GPU.

You need to add the following block after importing keras. I am working on a machine which have 56 core cpu, and a gpu.

import keras
import tensorflow as tf


config = tf.ConfigProto( device_count = {'GPU': 1 , 'CPU': 56} ) 
sess = tf.Session(config=config) 
keras.backend.set_session(sess)

Of course, this usage enforces my machines maximum limits. You can decrease cpu and gpu consumption values.


回答 2

2.0兼容答案:虽然上面提到的答案详细说明了如何在Keras Model上使用GPU,但我想说明如何实现Tensorflow Version 2.0

要知道有多少个GPU可用,我们可以使用以下代码:

print("Num GPUs Available: ", len(tf.config.experimental.list_physical_devices('GPU')))

要找出您的操作和张量分配给哪些设备,请将其tf.debugging.set_log_device_placement(True)作为程序的第一条语句。

启用设备放置日志记录将导致打印任何Tensor分配或操作。例如,运行以下代码:

tf.debugging.set_log_device_placement(True)

# Create some tensors
a = tf.constant([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])
b = tf.constant([[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]])
c = tf.matmul(a, b)

print(c)

给出如下所示的输出:

在设备/ job:localhost / replica:0 / task:0 / device:GPU:0 tf.Tensor([[22. 28.] [49. 64.]],shape =(2,2)中执行op MatMul dtype = float32)

有关更多信息,请参考此链接

2.0 Compatible Answer: While above mentioned answer explain in detail on how to use GPU on Keras Model, I want to explain how it can be done for Tensorflow Version 2.0.

To know how many GPUs are available, we can use the below code:

print("Num GPUs Available: ", len(tf.config.experimental.list_physical_devices('GPU')))

To find out which devices your operations and tensors are assigned to, put tf.debugging.set_log_device_placement(True) as the first statement of your program.

Enabling device placement logging causes any Tensor allocations or operations to be printed. For example, running the below code:

tf.debugging.set_log_device_placement(True)

# Create some tensors
a = tf.constant([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])
b = tf.constant([[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]])
c = tf.matmul(a, b)

print(c)

gives the Output shown below:

Executing op MatMul in device /job:localhost/replica:0/task:0/device:GPU:0 tf.Tensor( [[22. 28.] [49. 64.]], shape=(2, 2), dtype=float32)

For more information, refer this link


回答 3

当然。如果您在Tensorflow或CNTk后端上运行,则代码将默认在GPU设备上运行。但是,如果Theano后端,则可以使用以下代码

Theano标志:

“ THEANO_FLAGS = device = gpu,floatX = float32 python my_keras_script.py”

Of course. if you are running on Tensorflow or CNTk backends, your code will run on your GPU devices defaultly.But if Theano backends, you can use following

Theano flags:

“THEANO_FLAGS=device=gpu,floatX=float32 python my_keras_script.py”


回答 4

在任务管理器中查看脚本是否正在运行GPU。如果不是,请怀疑您的CUDA版本是您所使用的tensorflow版本的正确版本,其他答案已经建议了。

此外,需要使用适用于CUDA版本的适当CUDA DNN库,才能使用tensorflow运行GPU。从此处下载/提取它,并将DLL(例如cudnn64_7.dll)放入CUDA bin文件夹(例如C:\ Program Files \ NVIDIA GPU Computing Toolkit \ CUDA \ v10.1 \ bin)。

See if your script is running GPU in Task manager. If not, suspect your CUDA version is right one for the tensorflow version you are using, as the other answers suggested already.

Additionally, a proper CUDA DNN library for the CUDA version is required to run GPU with tensorflow. Download/extract it from here and put the DLL (e.g., cudnn64_7.dll) into CUDA bin folder (e.g., C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v10.1\bin).


如何在Jupyter中显示完整输出,而不仅仅是最后结果?

问题:如何在Jupyter中显示完整输出,而不仅仅是最后结果?

我希望Jupyter打印所有交互式输出,而不要打印,而不仅仅是最后的结果。怎么做?

范例:

a=3
a
a+1

我想展示

3
4

I want Jupyter to print all the interactive output without resorting to print, not only the last result. How to do it?

Example :

a=3
a
a+1

I would like to display

3
4


回答 0

感谢Thomas,这是我一直在寻找的解决方案:

from IPython.core.interactiveshell import InteractiveShell
InteractiveShell.ast_node_interactivity = "all"

Thanks to Thomas, here is the solution I was looking for:

from IPython.core.interactiveshell import InteractiveShell
InteractiveShell.ast_node_interactivity = "all"

回答 1

https://www.dataquest.io/blog/jupyter-notebook-tips-tricks-shortcuts/

1)将此代码放在Jupyter单元格中:

from IPython.core.interactiveshell import InteractiveShell

InteractiveShell.ast_node_interactivity = "all"

2)在Windows中,以下步骤使更改永久生效。应该适用于其他操作系统。您可能必须更改路径。

C:\Users\your_profile\\.ipython\profile_default

使用以下代码在profile_defaults中创建一个ipython_config.py文件:

c = get_config()

c.InteractiveShell.ast_node_interactivity = "all"

https://www.dataquest.io/blog/jupyter-notebook-tips-tricks-shortcuts/

1) Place this code in a Jupyter cell:

from IPython.core.interactiveshell import InteractiveShell

InteractiveShell.ast_node_interactivity = "all"

2) In Windows, the steps below makes the change permanent. Should work for other operating systems. You might have to change the path.

C:\Users\your_profile\\.ipython\profile_default

Make a ipython_config.py file in the profile_defaults with the following code:

c = get_config()

c.InteractiveShell.ast_node_interactivity = "all"

回答 2

每个笔记本的基础

正如其他人回答的那样,将以下代码放入Jupyter Lab或Jupyter Notebook单元将起作用:

from IPython.core.interactiveshell import InteractiveShell

InteractiveShell.ast_node_interactivity = "all"

永久改变

但是,如果您想永久保留它并使用Jupyter Lab,则需要创建一个IPython Notebook配置文件。运行以下命令来执行此操作(如果您使用Jupyter Notebook,则不要运行-以下是更多详细信息):

ipython profile create

如果您使用的是Jupyter Notebook,则应该已经创建了此文件,因此无需再次运行它。实际上,运行此命令可能会覆盖您当前的首选项。

创建此文件后,对于Jupyter Lab和Notebook用户一样,将以下代码添加到该文件中C:\Users\USERNAME\\.ipython\profile_default\ipython_config.py

c.InteractiveShell.ast_node_interactivity = "all"

我发现c = get_config()在新版本的Jupyter中没有必要 ,但是如果这对您不起作用,请c = get_config()在文件的开头添加。

有关以外的其他标志选项"all",请访问以下链接:https : //ipython.readthedocs.io/en/stable/config/options/terminal.html#configtrait-InteractiveShell.ast_node_interactivity

Per Notebook Basis

As others have answered, putting the following code in a Jupyter Lab or Jupyter Notebook cell will work:

from IPython.core.interactiveshell import InteractiveShell

InteractiveShell.ast_node_interactivity = "all"

Permanent Change

However, if you would like to make this permanent and use Jupyter Lab, you will need to create an IPython notebook config file. Run the following command to do so (DO NOT run if you use Jupyter Notebook – more details below):

ipython profile create

If you are using Jupyter Notebook, this file should have already been created and there will be no need to run it again. In fact, running this command may overwrite your current preferences.

Once you have this file created, for Jupyter Lab and Notebook users alike, add the following code to the file C:\Users\USERNAME\\.ipython\profile_default\ipython_config.py:

c.InteractiveShell.ast_node_interactivity = "all"

I found there is no need for c = get_config() in the newer versions of Jupyter, but if this doesn’t work for you, add the c = get_config() to the beginning of the file.

For more flag options other than "all", visit this link: https://ipython.readthedocs.io/en/stable/config/options/terminal.html#configtrait-InteractiveShell.ast_node_interactivity


如何知道Jupyter笔记本中正在运行哪个?

问题:如何知道Jupyter笔记本中正在运行哪个?

我在用于Python编程的浏览器中使用Jupyter笔记本,已经安装了Anaconda(Python 3.5)。但是我很确定Jupyter使用本地python解释器而不是anaconda运行我的python命令。如何更改它并将Anaconda用作解释器?

Ubuntu 16.10-Anaconda3

I use Jupyter notebook in a browser for Python programming, I have installed Anaconda (Python 3.5). But I’m quite sure that Jupyter in running my python commands with the native python interpreter and not with anaconda. How can I change it and use Anaconda as interpreter?

Ubuntu 16.10 — Anaconda3


回答 0

from platform import python_version

print(python_version())

这将为您提供运行脚本的python的确切版本。例如输出:

3.6.5
from platform import python_version

print(python_version())

This will give you the exact version of python running your script. eg output:

3.6.5

回答 1

import sys
sys.executable

会给你翻译。您可以在创建新笔记本时选择所需的解释器。确保您的anaconda解释器的路径已添加到您的路径中(最有可能在bashrc / bash_profile中的某个位置)。

例如,我以前在.bash_profile中有以下行,我是手动添加的:

export PATH="$HOME/anaconda3/bin:$PATH"

编辑:如评论中所述,这不是将anaconda添加到路径的正确方法。引用Anaconda的文档,应在安装后改为使用以下方法conda init

我应该将Anaconda添加到macOS或Linux PATH吗?

我们不建议手动将Anaconda添加到PATH。在安装过程中,系统将询问您“是否希望安装程序通过运行conda init来初始化Anaconda3?” 我们建议“是”。如果输入“ no”,则conda根本不会修改您的Shell脚本。为了在安装过程完成后进行初始化,请先运行source <path to conda>/bin/activate然后再运行conda init

import sys
sys.executable

will give you the interpreter. You can select the interpreter you want when you create a new notebook. Make sure the path to your anaconda interpreter is added to your path (somewhere in your bashrc/bash_profile most likely).

For example I used to have the following line in my .bash_profile, that I added manually :

export PATH="$HOME/anaconda3/bin:$PATH"

EDIT: As mentioned in a comment, this is not the proper way to add anaconda to the path. Quoting Anaconda’s doc, this should be done instead after install, using conda init:

Should I add Anaconda to the macOS or Linux PATH?

We do not recommend adding Anaconda to the PATH manually. During installation, you will be asked “Do you wish the installer to initialize Anaconda3 by running conda init?” We recommend “yes”. If you enter “no”, then conda will not modify your shell scripts at all. In order to initialize after the installation process is done, first run source <path to conda>/bin/activate and then run conda init


回答 2

import sys
print(sys.executable)
print(sys.version)
print(sys.version_info)

见下文:-当我在CONDA venv之外运行JupyterNotebook时的输出

/home/dhankar/anaconda2/bin/python
2.7.12 |Anaconda 4.2.0 (64-bit)| (default, Jul  2 2016, 17:42:40) 
[GCC 4.4.7 20120313 (Red Hat 4.4.7-1)]
sys.version_info(major=2, minor=7, micro=12, releaselevel='final', serial=0)
 

当我在使用命令创建的CONDA Venv中运行相同的JupyterNoteBook时看到以下内容-

conda create -n py35 python=3.5 ## Here - py35 , is name of my VENV

在我的Jupyter笔记本中打印:

/home/dhankar/anaconda2/envs/py35/bin/python
3.5.2 |Continuum Analytics, Inc.| (default, Jul  2 2016, 17:53:06) 
[GCC 4.4.7 20120313 (Red Hat 4.4.7-1)]
sys.version_info(major=3, minor=5, micro=2, releaselevel='final', serial=0)

另外,如果您已经使用不同版本的Python创建了各种VENV,则可以通过从JupyterNotebook菜单中选择KERNEL >> CHANGE KERNEL切换到所需的内核… JupyterNotebookScreencapture

还要在现有的CONDA虚拟环境中安装ipykernel-

http://ipython.readthedocs.io/en/stable/install/kernel_install.html#kernels-for-different-environments

来源-https ://github.com/jupyter/notebook/issues/1524

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

安装IPython内核规范。

可选参数:-h,–help显示此帮助消息并退出–user为当前用户而不是系统范围内安装–name NAME指定kernelspec的名称。需要同时具有多个IPython内核。–display-name DISPLAY_NAME指定kernelspec的显示名称。当您有多个IPython内核时,这将很有帮助。–profile PROFILE指定要加载的IPython配置文件。这可以用来创建内核的自定义版本。–prefix PREFIX为kernelspec指定安装前缀。需要将其安装到非默认位置,例如conda / virtual-env。–sys-prefix安装到Python的sys.prefix。–prefix =’/ Users / bussonniermatthias / anaconda’的简写。用于conda / virtual-envs。

 import sys
 print(sys.executable)
 print(sys.version)
 print(sys.version_info)

Seen below :- output when i run JupyterNotebook outside a CONDA venv

/home/dhankar/anaconda2/bin/python
2.7.12 |Anaconda 4.2.0 (64-bit)| (default, Jul  2 2016, 17:42:40) 
[GCC 4.4.7 20120313 (Red Hat 4.4.7-1)]
sys.version_info(major=2, minor=7, micro=12, releaselevel='final', serial=0)

Seen below when i run same JupyterNoteBook within a CONDA Venv created with command —

conda create -n py35 python=3.5 ## Here - py35 , is name of my VENV

in my Jupyter Notebook it prints :-

/home/dhankar/anaconda2/envs/py35/bin/python
3.5.2 |Continuum Analytics, Inc.| (default, Jul  2 2016, 17:53:06) 
[GCC 4.4.7 20120313 (Red Hat 4.4.7-1)]
sys.version_info(major=3, minor=5, micro=2, releaselevel='final', serial=0)

also if you already have various VENV’s created with different versions of Python you switch to the desired Kernel by choosing KERNEL >> CHANGE KERNEL from within the JupyterNotebook menu… JupyterNotebookScreencapture

Also to install ipykernel within an existing CONDA Virtual Environment –

http://ipython.readthedocs.io/en/stable/install/kernel_install.html#kernels-for-different-environments

Source — https://github.com/jupyter/notebook/issues/1524

 $ /path/to/python -m  ipykernel install --help
 usage: ipython-kernel-install [-h] [--user] [--name NAME]
                          [--display-name DISPLAY_NAME]
                          [--profile PROFILE] [--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. –profile PROFILE Specify an IPython profile to load. This can be used to create custom versions of the kernel. –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.


回答 3

假设您的后端系统错误,则可以kernel通过kernel.jsonkernelsjupyter数据路径的文件夹中创建新的或编辑现有的后端来更改后端jupyter --paths。您可以有多个内核(R,Python2,Python3(+ virtualenvs),Haskell),例如,可以创建一个Anaconda特定的内核:

$ <anaconda-path>/bin/python3 -m ipykernel install --user --name anaconda --display-name "Anaconda"

应该创建一个新内核:

<jupyter-data-dir>/kernels/anaconda/kernel.json

{
    "argv": [ "<anaconda-path>/bin/python3", "-m", "ipykernel", "-f", "{connection_file}" ],
    "display_name": "Anaconda",
    "language": "python"
}

您需要确保ipykernel在anaconda发行版中安装了软件包。

这样,您就可以在内核之间切换,并使用不同的内核使用不同的笔记本。

Assuming you have the wrong backend system you can change the backend kernel by creating a new or editing the existing kernel.json in the kernels folder of your jupyter data path jupyter --paths. You can have multiple kernels (R, Python2, Python3 (+virtualenvs), Haskell), e.g. you can create an Anaconda specific kernel:

$ <anaconda-path>/bin/python3 -m ipykernel install --user --name anaconda --display-name "Anaconda"

Should create a new kernel:

<jupyter-data-dir>/kernels/anaconda/kernel.json

{
    "argv": [ "<anaconda-path>/bin/python3", "-m", "ipykernel", "-f", "{connection_file}" ],
    "display_name": "Anaconda",
    "language": "python"
}

You need to ensure ipykernel package is installed in the anaconda distribution.

This way you can just switch between kernels and have different notebooks using different kernels.


回答 4

为Jupyter Notebook创建虚拟环境

最小的Python安装是

sudo apt install python3.7 python3.7-venv python3.7-minimal python3.7-distutils python3.7-dev python3.7-gdbm python3-gdbm-dbg python3-pip

然后您可以创建和使用环境

/usr/bin/python3.7 -m venv test
cd test
source test/bin/activate
pip install jupyter matplotlib seaborn numpy pandas scipy
# install other packages you need with pip/apt
jupyter notebook
deactivate

您可以使用以下命令为Jupyter创建内核

ipython3 kernel install --user --name=test

Creating a virtual environment for Jupyter Notebooks

A minimal Python install is

sudo apt install python3.7 python3.7-venv python3.7-minimal python3.7-distutils python3.7-dev python3.7-gdbm python3-gdbm-dbg python3-pip

Then you can create and use the environment

/usr/bin/python3.7 -m venv test
cd test
source test/bin/activate
pip install jupyter matplotlib seaborn numpy pandas scipy
# install other packages you need with pip/apt
jupyter notebook
deactivate

You can make a kernel for Jupyter with

ipython3 kernel install --user --name=test

如何腌制或存储Jupyter(IPython)笔记本会话以供以后使用

问题:如何腌制或存储Jupyter(IPython)笔记本会话以供以后使用

假设我正在Jupyter / Ipython笔记本中进行较大的数据分析,并且完成了大量耗时的计算。然后,由于某种原因,我必须关闭jupyter本地服务器I,但是我想稍后再进行分析,而不必再次进行所有耗时的计算。


我想什么爱做的是pickle或存储整个Jupyter会话(所有大熊猫dataframes,np.arrays,变量,…),所以我可以放心地关闭服务器知道我可以在完全相同的状态返回到我的会话之前。

从技术上讲甚至可行吗?有没有我忽略的内置功能?


编辑:根据这个答案,有一种%store 魔法应该是“轻型泡菜”。但是,您必须像这样手动存储变量:

#inside a ipython/nb session
foo = "A dummy string"
%store foo
关闭种子,重新启动内核#r
%store -r foo进行刷新
print(foo) # "A dummy string"

这与我想要的功能相当接近,但是由于必须手动执行并且无法区分不同的会话,因此它的用处不大。

Let’s say I am doing a larger data analysis in Jupyter/Ipython notebook with lots of time consuming computations done. Then, for some reason, I have to shut down the jupyter local server I, but I would like to return to doing the analysis later, without having to go through all the time-consuming computations again.


What I would like love to do is pickle or store the whole Jupyter session (all pandas dataframes, np.arrays, variables, …) so I can safely shut down the server knowing I can return to my session in exactly the same state as before.

Is it even technically possible? Is there a built-in functionality I overlooked?


EDIT: based on this answer there is a %store magic which should be “lightweight pickle”. However you have to store the variables manually like so:

#inside a ipython/nb session
foo = "A dummy string"
%store foo
closing seesion, restarting kernel
%store -r foo # r for refresh
print(foo) # "A dummy string"

which is fairly close to what I would want, but having to do it manually and being unable to distinguish between different sessions makes it less useful.


回答 0

我认为迪尔很好地回答了您的问题。

pip install dill

保存笔记本会话:

import dill
dill.dump_session('notebook_env.db')

恢复笔记本会话:

import dill
dill.load_session('notebook_env.db')

资源

I think Dill answers your question well.

pip install dill

Save a Notebook session:

import dill
dill.dump_session('notebook_env.db')

Restore a Notebook session:

import dill
dill.load_session('notebook_env.db')

Source


回答 1

(我宁愿评论而不愿将其作为实际答案,但我需要更多的声誉才能发表评论。)

您可以系统地存储大多数类似数据的变量。我通常要做的是将所有数据帧,数组等存储在pandas.HDFStore中。在笔记本的开头,声明

backup = pd.HDFStore('backup.h5')

然后在产生它们时存储任何新变量

backup['var1'] = var1

最后,可能是一个好主意

backup.close()

在关闭服务器之前。下次您想继续使用笔记本时:

backup = pd.HDFStore('backup.h5')
var1 = backup['var1']

说实话,我也更喜欢ipython Notebook中的内置功能。您不能以这种方式保存所有内容(例如,对象,连接),并且很难用大量样板代码来组织笔记本。

(I’d rather comment than offer this as an actual answer, but I need more reputation to comment.)

You can store most data-like variables in a systematic way. What I usually do is store all dataframes, arrays, etc. in pandas.HDFStore. At the beginning of the notebook, declare

backup = pd.HDFStore('backup.h5')

and then store any new variables as you produce them

backup['var1'] = var1

At the end, probably a good idea to do

backup.close()

before turning off the server. The next time you want to continue with the notebook:

backup = pd.HDFStore('backup.h5')
var1 = backup['var1']

Truth be told, I’d prefer built-in functionality in ipython notebook, too. You can’t save everything this way (e.g. objects, connections), and it’s hard to keep the notebook organized with so much boilerplate codes.


回答 2

这个问题涉及到:如何在IPython Notebook中进行缓存?

为了保存单个单元的结果,缓存魔术派上了用场。

%%cache longcalc.pkl var1 var2 var3
var1 = longcalculation()
....

重新运行笔记本时,将从高速缓存中加载此单元格的内容。

这不能完全回答您的问题,但是对于所有冗长的计算结果都可以快速恢复的情况,这可能就足够了。这对我来说是一个可行的解决方案,同时点击了笔记本顶部的“ run-all”按钮。

缓存魔法救不了整个笔记本的状态还没有。据我所知,还没有其他系统可以恢复“笔记本”。这将需要保存python内核的所有历史记录。加载笔记本电脑并连接到内核后,应加载此信息。

This question is related to: How to cache in IPython Notebook?

To save the results of individual cells, the caching magic comes in handy.

%%cache longcalc.pkl var1 var2 var3
var1 = longcalculation()
....

When rerunning the notebook, the contents of this cell is loaded from the cache.

This is not exactly answering your question, but it might be enough to when the results of all the lengthy calculations are recovered fast. This in combination of hitting the run-all button on top of the notebook is for me a workable solution.

The cache magic cannot save the state of a whole notebook yet. To my knowledge there is no other system yet to resume a “notebook”. This would require to save all the history of the python kernel. After loading the notebook, and connecting to a kernel, this information should be loaded.


如何与非程序员共享Jupyter笔记本?[关闭]

问题:如何与非程序员共享Jupyter笔记本?[关闭]

我试图用Jupyter做我不能做的事情。

我的内部服务器上运行着Jupyter服务器,可通过VPN和受密码保护的服务器进行访问。

我是唯一实际创建笔记本的人,但是我想以只读方式使其他团队成员可以看到一些笔记本。理想情况下,我可以与他们共享一个URL,当他们希望查看带有刷新数据的笔记本时,他们将为其添加书签。

我看到了导出选项,但找不到任何有关“发布”或“公开”本地现场笔记本的信息。这不可能吗?考虑应该如何使用Jupyter可能只是错误的方式?

I am trying to wrap my head around what I can/cannot do with Jupyter.

I have a Jupyter server running on our internal server, accessible via VPN and password protected.

I am the only one actually creating notebooks but I would like to make some notebooks visible to other team members in a read-only way. Ideally I could just share a URL with them that they would bookmark for when they want to see the notebook with refreshed data.

I saw export options but cannot find any mention of “publishing” or “making public” local live notebooks. Is this impossible? Is it maybe just a wrong way to think about how Jupyter should be used?


回答 0

共享Jupyter笔记本的“最佳”方法是将其放置在GitHub(直接查看)或其他公共链接上,然后使用Jupyter Notebook Viewer。当隐私更多是一个问题时,可以有其他选择,但肯定会更复杂。仅Jupyter并没有内置的方法来执行此操作,但是有两个选项:

托管您自己的nbviewer

GitHub和Jupyter Notebook Veiwer都使用相同的工具将.ipynb文件呈现为静态HTML,此工具为nbviewer

安装说明比我愿意介绍的要复杂,但是如果您的公司/团队拥有不需要密码访问的共享服务器,则可以在该服务器上托管nbviewer并指示其从您的凭据服务器加载。这可能需要比您将在文档中找到的配置更高级的配置。

设置部署脚本

如果您不一定需要实时更新HTML,则可以在有证书的服务器上设置一个脚本,该脚本将仅使用Jupyter的内置导出选项来创建静态HTML文件,然后将其发送到更易于访问的服务器上。

The “best” way to share a Jupyter notebook is to simply to place it on GitHub (and view it directly) or some other public link and use the Jupyter Notebook Viewer. When privacy is more of an issue then there are alternatives but it’s certainly more complex; there’s no built-in way to do this in Jupyter alone, but a couple of options are:

Host your own nbviewer

GitHub and the Jupyter Notebook Veiwer both use the same tool to render .ipynb files into static HTML, this tool is nbviewer.

The installation instructions are more complex than I’m willing to go into here but if your company/team has a shared server that doesn’t require password access then you could host the nbviewer on that server and direct it to load from your credentialed server. This will probably require some more advanced configuration than you’re going to find in the docs.

Set up a deployment script

If you don’t necessarily need live updating HTML then you could set up a script on your credentialed server that will simply use Jupyter’s built-in export options to create the static HTML files and then send those to a more publicly accessible server.


回答 1

Google最近公开了其内部协作项目(此处链接)。您可以使用与启动Google表格或Google文档相同的方式来启动笔记本,然后简单地共享笔记本或添加协作者。

目前,这对我来说是最简单的方法。

Google has recently made public its internal Collaboratory project (link here). You can start a notebook in the same way as starting a Google Sheet or Google Doc, and then simply share the notebook or add collaborators..

For now, this is the easiest way for me.


回答 2

迈克尔建议运行自己的nbviewer实例是我过去在Enterprise Github服务器上使用的一个很好的建议。

另一个轻量级替代方法是在笔记本的末尾有一个单元格,该单元格对nbconvert进行shell调用,以便在运行整个过程后自动刷新该单元格:

!ipython nbconvert <notebook name>.ipynb --to html

编辑:使用Jupyter / IPython的Big Split,您可能需要将其更改为!jupyter nbconvert <notebook name>.ipynb --to html现在。

Michael’s suggestion of running your own nbviewer instance is a good one I used in the past with an Enterprise Github server.

Another lightweight alternative is to have a cell at the end of your notebook that does a shell call to nbconvert so that it’s automatically refreshed after running the whole thing:

!ipython nbconvert <notebook name>.ipynb --to html

EDIT: With Jupyter/IPython’s Big Split, you’ll probably want to change this to !jupyter nbconvert <notebook name>.ipynb --to html now.


回答 3

这取决于您打算如何使用笔记本电脑:您是否希望用户可以重新计算结果或只是玩游戏?

静态笔记本

NBViewer是一个很棒的工具。您可以在Jupyter中直接使用它。Github也有一个渲染器,因此您可以直接链接文件(例如https://github.com/my-name/my-repo/blob/master/mynotebook.ipynb

活着的笔记本

如果希望用户能够重新计算某些部分,则也可以使用MyBinder。启动笔记本需要花费一些时间,但是这样做值得。

正如@Mapl称,谷歌可以承载您的笔记本Colab。一项不错的功能是通过GPU计算单元。

It depends on what you are intending to do with your Notebook: do you want that the user can recompute the results or just playing with them?

Static notebook

NBViewer is a great tool. You can directly use it inside Jupyter. Github has also a render, so you can directly link your file (such as https://github.com/my-name/my-repo/blob/master/mynotebook.ipynb)

Alive notebook

If you want your user to be able to recompute some parts, you can also use MyBinder. It takes some time to start your notebook, but the result is worth it.

As said by @Mapl, Google can host your notebook with Colab. A nice feature is to compute your cells over a GPU.


回答 4

在WordPress上执行此操作的一种好方法包括以下步骤:

步骤1:在文本编辑器中打开Jupyter笔记本,然后复制内容,如下所示: 在文本编辑器中打开您的.ipynb文件时,可能看起来像这样

步骤2: 按Ctrl + ACtrl + C此内容。然后按Ctrl + V到您应该创建的GitHub Gist。

第3步:创建公共要点,然后像通常将要点要嵌入到WordPress一样,将要点嵌入,请转到HTML编辑器并按如下所示添加:

[gist gist_url]

我实际上已经在我的博客上实现了此功能。你可以在这里找到帖子

A great way of doing this on WordPress consists of the following steps:

Step 1: Open your Jupyter notebook in a text editor and copy the content which may look like so: Your .ipynb file may look like this when opened in a text editor

Step 2: Ctrl + A and Ctrl + C this content. Then Ctrl + V this to a GitHub Gist that you should create.

Step 3: Create a public gist and embed the gist like you always embed gists on WordPress, viz., go to the HTML editor and add like so:

[gist gist_url]

I have actually implemented this on my blog. You can find the post here


回答 5

实现此目标的一种方法是使用JupyterHub

使用JupyterHub,您可以创建一个多用户中心,该中心可以生成,管理和代理单用户Jupyter笔记本服务器的多个实例。由于其灵活性和定制选项,JupyterHub可用于为学生,公司数据科学小组或科研小组的笔记本电脑提供服务。

One more way to achieve this goal would be using JupyterHub.

With JupyterHub you can create a multi-user Hub which spawns, manages, and proxies multiple instances of the single-user Jupyter notebook server. Due to its flexibility and customization options, JupyterHub can be used to serve notebooks to a class of students, a corporate data science group, or a scientific research group.


如何在IPython Notebook Server 3中看到函数参数?

问题:如何在IPython Notebook Server 3中看到函数参数?

我最近切换到了Anaconda版本的IPython Notebook 3(确切地说是3.1.0-cbccb68)。以前,当我键入一个函数并打开一个这样的括号时:

time.sleep()

如果光标在括号之间,那么我将获得一个显示功能参数的上下文覆盖菜单。现在,我没有看到它,尽管已经搜索了,但仍然找不到如何打开此功能的方法。

I’ve recently switched to IPython Notebook 3 (3.1.0-cbccb68 to be exact), the Anaconda version. Previously when I typed a function and opened a parenthesis like this:

time.sleep()

and if the cursor was between the parentheses then I would get a contextual overlay menu that displayed the function arguments. Now I don’t see it, and although I’ve searched, I can’t find out how I can turn on this functionality.


回答 0

在1.0中,该功能被绑定到(tabshift-tab,在2.0 tab被废弃,但仍具有功能在某些情况下,明确的完成或检查在许多情况下被竞争。建议始终使用shift-Tab(在类似Haskell的语法中,它也被添加为令人讨厌的不推荐使用,因为它在更多情况下也可以将人们推向Shift-Tab。在3.0中,已弃用的绑定已被删除,以支持正式发布,现在已存在18个月以上Shift-Tab

因此按Shift-Tab

In 1.0, the functionality was bound to ( and tab and shift-tab, in 2.0 tab was deprecated but still functional in some unambiguous cases completing or inspecting were competing in many cases. Recommendation was to always use shift-Tab. ( was also added as deprecated as confusing in Haskell-like syntax to also push people toward Shift-Tab as it works in more cases. in 3.0 the deprecated bindings have been remove in favor of the official, present for 18+ month now Shift-Tab.

So press Shift-Tab.


回答 1

尝试Shift-Tab-Tab使用比更大的文档Shift-Tab。一样,但是您可以向下滚动。

Shift-Tab-Tab-Tab 在您输入时,工具提示会持续10秒钟。

Shift-Tab-Tab-Tab-Tab 并且文档字符串出现在寻呼机中(窗口底部的一小部分)并停留在该位置。

Try Shift-Tab-Tab a bigger documentation appears, than with Shift-Tab. It’s the same but you can scroll down.

Shift-Tab-Tab-Tab and the tooltip will linger for 10 seconds while you type.

Shift-Tab-Tab-Tab-Tab and the docstring appears in the pager (small part at the bottom of the window) and stays there.


回答 2

为@Thomas G的答案添加屏幕截图(示例)和更多上下文。

如果它不起作用,请确保您已经正确执行了代码。在这种情况下,请确保import pandas as pd已正确运行,然后再检查以下快捷方式。

()使用快捷方式之前,请将光标放在括号的中间。

shift + tab

显示简短的文档和少量参数

shift + tab + tab

使用滚动条扩展文档

shift + tab + tab + tab

提供带有工具提示的文档:“您键入时会停留10秒钟”。这意味着您可以编写参数并等待10秒。

shift + tab + tab + tab + tab

它在底部打开一个带有选项的小窗口(小窗口的右上角),以在新的浏览器选项卡中打开完整的文档。

Adding screen shots(examples) and some more context for the answer of @Thomas G.

if its not working please make sure if you have executed code properly. In this case make sure import pandas as pd is ran properly before checking below shortcut.

Place the cursor in middle of parenthesis () before you use shortcut.

shift + tab

Display short document and few params

shift + tab + tab

Expands document with scroll bar

shift + tab + tab + tab

Provides document with a Tooltip: “will linger for 10secs while you type”. which means it allows you write params and waits for 10secs.

shift + tab + tab + tab + tab

It opens a small window in bottom with option(top righ corner of small window) to open full documentation in new browser tab.


回答 3

Shift-Tab可让我查看产品

Shift-Tab works for me to view the dcoumentation


在jupyter笔记本中折叠单元格

问题:在jupyter笔记本中折叠单元格

我正在使用ipython Jupyter笔记本。假设我定义了一个在屏幕上占用很多空间的函数。有没有办法让牢房塌陷?

我希望函数保持执行和可调用状态,但是我想隐藏/折叠单元格以便更好地可视化笔记本。我怎样才能做到这一点?

I am using ipython Jupyter notebook. Let’s say I defined a function that occupies a lot of space on my screen. Is there a way to collapse the cell?

I want the function to remain executed and callable, yet I want to hide / collapse the cell in order to better visualize the notebook. How can I do this?


回答 0

jupyter contrib nbextensionsPython包包含一个代码折叠扩展,可以在笔记本内启用。请点击链接(Github)获得文档。

要使用命令行安装:

pip install jupyter_contrib_nbextensions
jupyter contrib nbextension install --user

为了使生活变得更轻松,我还建议您jupyter nbextensions configurator打包。这在笔记本电脑界面中提供了一个额外的选项卡,您可以在其中轻松地(停用)所有已安装的扩展程序。

安装:

pip install jupyter_nbextensions_configurator
jupyter nbextensions_configurator enable --user

The jupyter contrib nbextensions Python package contains a code-folding extension that can be enabled within the notebook. Follow the link (Github) for documentation.

To install using command line:

pip install jupyter_contrib_nbextensions
jupyter contrib nbextension install --user

To make life easier in managing them, I’d also recommend the jupyter nbextensions configurator package. This provides an extra tab in your Notebook interface from where you can easily (de)activate all installed extensions.

Installation:

pip install jupyter_nbextensions_configurator
jupyter nbextensions_configurator enable --user

回答 1

您可以创建一个单元格并将以下代码放入其中:

%%html
<style>
div.input {
    display:none;
}
</style>

运行此单元格将隐藏所有输入单元格。要显示它们,可以使用菜单清除所有输出。

否则,您可以尝试以下笔记本扩展:

https://github.com/ipython-contrib/IPython-notebook-extensions/wiki/Home_3x

You can create a cell and put the following code in it:

%%html
<style>
div.input {
    display:none;
}
</style>

Running this cell will hide all input cells. To show them back, you can use the menu to clear all outputs.

Otherwise you can try notebook extensions like below:

https://github.com/ipython-contrib/IPython-notebook-extensions/wiki/Home_3x


回答 2

JupyterLab支持细胞折叠。单击左侧的蓝色单元格栏将折叠该单元格。

JupyterLab supports cell collapsing. Clicking on the blue cell bar on the left will fold the cell.


回答 3

我遇到了类似的问题,@ Energya指出的“ nbextensions”工作得非常好,很轻松。对于笔记本扩展及其配置程序,安装说明很简单(我在Windows上使用anaconda进行了尝试)。

就是说,我想补充一点,以下扩展应该引起关注。

  • 隐藏输入| 此扩展允许在笔记本中隐藏单个码元。这可以通过单击工具栏按钮来实现:

  • 可折叠的标题| 允许笔记本具有可折叠的部分,并以标题分隔

  • 代码折叠| 已经提到过,但是为了完整性我添加了它

I had a similar issue and the “nbextensions” pointed out by @Energya worked very well and effortlessly. The install instructions are straight forward (I tried with anaconda on Windows) for the notebook extensions and for their configurator.

That said, I would like to add that the following extensions should be of interest.

  • Hide Input | This extension allows hiding of an individual codecell in a notebook. This can be achieved by clicking on the toolbar button:

  • Collapsible Headings | Allows notebook to have collapsible sections, separated by headings

  • Codefolding | This has been mentioned but I add it for completeness


回答 4

在〜/ .jupyter / custom /内创建具有以下内容的custom.js文件:

$("<style type='text/css'> .cell.code_cell.collapse { max-height:30px; overflow:hidden;} </style>").appendTo("head");
$('.prompt.input_prompt').on('click', function(event) {
    console.log("CLICKED", arguments)   
    var c = $(event.target.closest('.cell.code_cell'))
    if(c.hasClass('collapse')) {
        c.removeClass('collapse');
    } else {
        c.addClass('collapse');
    }
});

保存后,重新启动服务器并刷新笔记本。您可以通过单击输入标签(In [])折叠任何单元格。

Create custom.js file inside ~/.jupyter/custom/ with following contents:

$("<style type='text/css'> .cell.code_cell.collapse { max-height:30px; overflow:hidden;} </style>").appendTo("head");
$('.prompt.input_prompt').on('click', function(event) {
    console.log("CLICKED", arguments)   
    var c = $(event.target.closest('.cell.code_cell'))
    if(c.hasClass('collapse')) {
        c.removeClass('collapse');
    } else {
        c.addClass('collapse');
    }
});

After saving, restart the server and refresh the notebook. You can collapse any cell by clicking on the input label (In[]).


回答 5

hide_code扩展名允许您隐藏单个单元格和/或它们旁边的提示。安装为

pip3 install hide_code

访问https://github.com/kirbs-/hide_code/了解有关此扩展程序的更多信息。

The hide_code extension allows you to hide individual cells, and/or the prompts next to them. Install as

pip3 install hide_code

Visit https://github.com/kirbs-/hide_code/ for more info about this extension.


回答 6

首先,按照Energya的指示进行:

pip install jupyter_contrib_nbextensions
jupyter contrib nbextension install --user
pip install jupyter_nbextensions_configurator
jupyter nbextensions_configurator enable --user

第二个关键是:打开木星笔记本后,单击Nbextension选项卡。现在,从Nbextension提供的搜索工具(不是Web浏览器)中搜索“ colla”,然后您将找到一个名为“ Collapsible Headings”的内容

这就是你想要的!

Firstly, follow Energya’s instruction:

pip install jupyter_contrib_nbextensions
jupyter contrib nbextension install --user
pip install jupyter_nbextensions_configurator
jupyter nbextensions_configurator enable --user

Second is the key: After opening jupiter notebook, click the Nbextension tab. Now Search “colla” from the searching tool provided by Nbextension(not by the web browser), then you will find something called “Collapsible Headings”

This is what you want!


回答 7

正如其他人所提到的,您可以通过nbextensions进行此操作。我想简短地解释一下我所做的事情:

要启用可协作的标题:在终端中,首先输入以下内容来启用/安装Jupyter Notebook Extensions:

pip install jupyter_contrib_nbextensions

然后输入:

jupyter contrib nbextension install

重新打开Jupyter Notebook。转到“编辑”选项卡,然后选择“ nbextensions配置”。取消直接在标题“ Configurable nbextensions”下的复选框,然后选择“可折叠标题”。

As others have mentioned, you can do this via nbextensions. I wanted to give the brief explanation of what I did, which was quick and easy:

To enable collabsible headings: In your terminal, enable/install Jupyter Notebook Extensions by first entering:

pip install jupyter_contrib_nbextensions

Then, enter:

jupyter contrib nbextension install

Re-open Jupyter Notebook. Go to “Edit” tab, and select “nbextensions config”. Un-check box directly under title “Configurable nbextensions”, then select “collapsible headings”.


回答 8

这个问题有很多答案,在许多扩展中,我觉得所有这些都不令人满意(有些比其他更好),例如代码折叠,标题折叠等。没有一个人以简单有效的方式满足我的要求。令我惊讶的是,尚未实施解决方案(对于Jupyter Lab而言)。

实际上,我非常不满意,以至于我开发了一个非常简单的笔记本扩展,可以扩展/折叠笔记本单元中的代码,同时保持其可执行性。

GitHub存储库:https : //github.com/BenedictWilkinsAI/cellfolding

以下是该扩展程序的小演示:

只需双击代码单元的左侧,即可将其折叠为一行:

再次双击将展开该单元格。

该扩展可以通过pip轻松安装:

pip install nbextension-cellfolding
jupyter nbextension install --py cellfolding --user
jupyter nbextension enable --py cellfolding --user 

并且还与nbextension configurator兼容。我希望人们会发现这很有用!

There are many answers to this question, all of which I feel are not satisfactory (some more than others), of the many extensions – code folding, folding by headings etc etc. None do what I want in simple and effective way. I am literally amazed that a solution has not been implemented (as it has for Jupyter Lab).

In fact, I was so dissatisfied that I have developed a very simple notebook extension that can expand/collapse the code in a notebook cell, while keeping it executable.

The GitHub repository: https://github.com/BenedictWilkinsAI/cellfolding

Below is a small demo of what the extension does:

Simply double clicking left of the code cell will collapse it to a single line:

Double clicking again will expand the cell.

The extension can be installed easily with pip:

pip install nbextension-cellfolding
jupyter nbextension install --py cellfolding --user
jupyter nbextension enable --py cellfolding --user 

and is also compatible with nbextension configurator. I hope that people will find this useful!


回答 9

潘岩建议的改进版本。它添加了显示代码单元的按钮:

%%html
<style id=hide>div.input{display:none;}</style>
<button type="button" 
onclick="var myStyle = document.getElementById('hide').sheet;myStyle.insertRule('div.input{display:inherit !important;}', 0);">
Show inputs</button>

或python:

# Run me to hide code cells

from IPython.core.display import display, HTML
display(HTML(r"""<style id=hide>div.input{display:none;}</style><button type="button"onclick="var myStyle = document.getElementById('hide').sheet;myStyle.insertRule('div.input{display:inherit !important;}', 0);">Show inputs</button>"""))

There’s also an improved version of Pan Yan suggestion. It adds the button that shows code cells back:

%%html
<style id=hide>div.input{display:none;}</style>
<button type="button" 
onclick="var myStyle = document.getElementById('hide').sheet;myStyle.insertRule('div.input{display:inherit !important;}', 0);">
Show inputs</button>

Or python:

# Run me to hide code cells

from IPython.core.display import display, HTML
display(HTML(r"""<style id=hide>div.input{display:none;}</style><button type="button"onclick="var myStyle = document.getElementById('hide').sheet;myStyle.insertRule('div.input{display:inherit !important;}', 0);">Show inputs</button>"""))

回答 10

除了启用扩展,您不需要做太多事情:

http://localhost:8888/nbextensions?nbextension=collapsible_headings
http://localhost:8888/nbextensions?nbextension=codefolding/main

最有可能在以下位置找到所有扩展:

http://localhost:8888/nbextensions

You don’t need to do much except to enable the extensions:

http://localhost:8888/nbextensions?nbextension=collapsible_headings
http://localhost:8888/nbextensions?nbextension=codefolding/main

Most probable you will find all your extensions in here:

http://localhost:8888/nbextensions


回答 11

我用来获得预期结果的是:

  1. 将以下代码块保存toggle_cell.py在与笔记本相同目录中的文件中
from IPython.core.display import display, HTML
toggle_code_str = '''
<form action="javascript:code_toggle()"><input type="submit" id="toggleButton" value="Show Sloution"></form>
'''

toggle_code_prepare_str = '''
    <script>
    function code_toggle() {
        if ($('div.cell.code_cell.rendered.selected div.input').css('display')!='none'){
            $('div.cell.code_cell.rendered.selected div.input').hide();
        } else {
            $('div.cell.code_cell.rendered.selected div.input').show();
        }
    }
    </script>

'''

display(HTML(toggle_code_prepare_str + toggle_code_str))

def hide_sloution():
    display(HTML(toggle_code_str))
  1. 在笔记本的第一个单元格中添加以下内容
from toggle_cell import toggle_code as hide_sloution
  1. 您需要添加切换按钮即可调用的任何单元格 hide_sloution()

What I use to get the desired outcome is:

  1. Save the below code block in a file named toggle_cell.py in the same directory as of your notebook
from IPython.core.display import display, HTML
toggle_code_str = '''
<form action="javascript:code_toggle()"><input type="submit" id="toggleButton" value="Show Sloution"></form>
'''

toggle_code_prepare_str = '''
    <script>
    function code_toggle() {
        if ($('div.cell.code_cell.rendered.selected div.input').css('display')!='none'){
            $('div.cell.code_cell.rendered.selected div.input').hide();
        } else {
            $('div.cell.code_cell.rendered.selected div.input').show();
        }
    }
    </script>

'''

display(HTML(toggle_code_prepare_str + toggle_code_str))

def hide_sloution():
    display(HTML(toggle_code_str))
  1. Add the following in the first cell of your notebook
from toggle_cell import toggle_code as hide_sloution
  1. Any cell you need to add the toggle button to simply call hide_sloution()

在IPython / Jupyter笔记本中显示行号

问题:在IPython / Jupyter笔记本中显示行号

在IPython / Jupyter Notebook中运行的大多数语言内核的错误报告都指出发生错误的行;但是(至少默认情况下)在笔记本电脑中没有显示行号。

是否可以将行号添加到IPython / Jupyter Notebook?

Error reports from most language kernels running in IPython/Jupyter Notebooks indicate the line on which the error occurred; but (at least by default) no line numbers are indicated in Notebooks.

Is it possibile to add the line numbers to IPython/Jupyter Notebooks?


回答 0

CTRLML在CodeMirror区域中切换行号。有关其他键盘快捷键,请参见快速帮助。

更详细地讲CTRLM(或ESC)将您带入命令模式,然后L按键将切换当前单元格行号的可见性。在较新的笔记本电脑版本中,Shift-L应切换所有单元格。

如果您忘记了快捷方式,请调出命令面板Ctrl-Shift+PCmd+Shift+P在Mac上为Mac,然后搜索“行号”),它应该允许切换并显示快捷方式。

CTRLML toggles line numbers in the CodeMirror area. See the QuickHelp for other keyboard shortcuts.

In more details CTRLM (or ESC) bring you to command mode, then pressing the L keys should toggle the visibility of current cell line numbers. In more recent notebook versions Shift-L should toggle for all cells.

If you can’t remember the shortcut, bring up the command palette Ctrl-Shift+P (Cmd+Shift+P on Mac), and search for “line numbers”), it should allow to toggle and show you the shortcut.


回答 1

在IPython 2.2.0上,只需在命令模式(通过键入Esc激活)中键入l(小写L)即可。有关其他快捷方式,请参见[帮助]-[键盘快捷方式]。

另外,您可以设置默认行为以通过编辑显示行号custom.js

On IPython 2.2.0, just typing l (lowercase L) on command mode (activated by typing Esc) works. See [Help] – [Keyboard Shortcuts] for other shortcuts.

Also, you can set default behavior to display line numbers by editing custom.js.


回答 2

View->中选择切换行号选项 Toggle Line Number

Select the Toggle Line Number Option from the View -> Toggle Line Number.


回答 3

要在启动时默认打开所有单元中的行号,我建议使用此链接。我引用:

  1. 导航到jupyter配置目录,您可以通过在命令行中键入以下内容来找到该目录:

    jupyter --config-dir
  2. 从那里打开或创建custom文件夹。

  3. 在该文件夹中,您应该找到一个custom.js文件。如果没有,则应该可以创建一个。在文本编辑器中将其打开并添加以下代码:

    define([
        'base/js/namespace',
        'base/js/events'
        ],
        function(IPython, events) {
            events.on("app_initialized.NotebookApp",
                function () {
                    IPython.Cell.options_default.cm_config.lineNumbers = true;
                }
            );
        }
    );

To turn line numbers on by default in all cells at startup I recommend this link. I quote:

  1. Navigate to your jupyter config directory, which you can find by typing the following at the command line:

    jupyter --config-dir
    
  2. From there, open or create the custom folder.

  3. In that folder, you should find a custom.js file. If there isn’t one, you should be able to create one. Open it in a text editor and add this code:

    define([
        'base/js/namespace',
        'base/js/events'
        ],
        function(IPython, events) {
            events.on("app_initialized.NotebookApp",
                function () {
                    IPython.Cell.options_default.cm_config.lineNumbers = true;
                }
            );
        }
    );
    

回答 4

为了我, ctrl + m用于将网页另存为png,因此无法正常工作。但是我找到了另一种方式。

在工具栏上,有一个名为打开命令paletee的底部,您可以单击它并键入该行,并在此处看到切换单元格的行号。

For me, ctrl + m is used to save the webpage as png, so it does not work properly. But I find another way.

On the toolbar, there is a bottom named open the command paletee, you can click it and type in the line, and you can see the toggle cell line number here.


回答 5

这是了解活动快捷方式的方法(取决于您的操作系统和笔记本电脑的版本,它可能会更改)

Help > Keyboard Shortcuts > toggle line numbers

在运行ipython3的OSX上, ESC L

Here is how to know active shortcut (depending on your OS and notebook version, it might change)

Help > Keyboard Shortcuts > toggle line numbers

On OSX running ipython3 it was ESC L


回答 6

您还可以Toggle Line NumbersView浏览器的Jupyter笔记本顶部工具栏上的下找到。这将添加/删除所有行号笔记本单元。

对我而言,Esc+ l仅添加/删除了活动单元格的行号。

You can also find Toggle Line Numbers under View on the top toolbar of the Jupyter notebook in your browser. This adds/removes the lines numbers in all notebook cells.

For me, Esc+l only added/removed the line numbers of the active cell.


回答 7

正在寻找这个:Shift-L在JupyterLab 1.0.0中

Was looking for this: Shift-L in JupyterLab 1.0.0


回答 8

1.按esc进入命令模式2.按l(小写L)显示行号

1.press esc to enter the command mode 2.perss l(it L in lowcase) to show the line number


删除Conda环境

问题:删除Conda环境

我想删除使用conda创建的特定环境。我该如何实现?假设我有一个活跃的testenv环境。我通过遵循文档尝试了:

$ conda env remove

CondaEnvironmentError: cannot remove current environment. deactivate and run conda remove again

然后我将其停用:

$ source deactivate

我尝试再次运行命令将其删除,但仍然出现相同的错误。这是怎么了?

I want to remove a certain environment created with conda. How can I achieve that? Let’s say I have an active testenv environment. I tried, by following documentation, with:

$ conda env remove

CondaEnvironmentError: cannot remove current environment. deactivate and run conda remove again

I then deactivate it:

$ source deactivate

I try running again the command to remove it and I still get the same error. What is going wrong here?


回答 0

您可能没有完全停用Conda环境-请记住,您需要在Conda中使用的命令是conda deactivate(对于旧版本,请使用source deactivate)。因此,在尝试之前,启动一个新的Shell并在其中激活环境可能是明智的。然后停用它。

您可以使用以下命令

conda env remove -n ENV_NAME

删除具有该名称的环境。(--name等于-n

请注意,您也可以将环境放置在要使用的任何位置,-p /path/to/env而不是-n ENV_NAME同时创建和删除环境(如果选择)。他们不具备住在你的畅达安装。

更新,2019年1月30日:从Conda 4.6起,该conda activate命令成为激活所有平台环境的新官方方式。更改在此Anaconda博客文章中进行了描述

You probably didn’t fully deactivate the Conda environment – remember, the command you need to use with Conda is conda deactivate (for older versions, use source deactivate). So it may be wise to start a new shell and activate the environment in that before you try. Then deactivate it.

You can use the command

conda env remove -n ENV_NAME

to remove the environment with that name. (--name is equivalent to -n)

Note that you can also place environments anywhere you want using -p /path/to/env instead of -n ENV_NAME when both creating and deleting environments, if you choose. They don’t have to live in your conda installation.

UPDATE, 30 Jan 2019: From Conda 4.6 onwards the conda activate command becomes the new official way to activate an environment across all platforms. The changes are described in this Anaconda blog post


回答 1

确保您的环境未处于活动状态后,键入:

$ conda env remove --name ENVIRONMENT

After making sure your environment is not active, type:

$ conda env remove --name ENVIRONMENT

回答 2

官方文档对我有用:

conda remove --name myenv --all

或者只是conda env remove --name myenv

要验证是否已删除环境,请在您的终端窗口或Anaconda Prompt中运行:

conda info --envs

显示的环境列表不应显示已删除的环境。

您的anaconda3环境文件夹可能会在anaconda3安装文件夹中列出已删除环境的空文件夹,例如:

/opt/anaconda3/envs

Official documentation way worked for me:

conda remove --name myenv --all

Or just conda env remove --name myenv.

To verify that the environment was removed, in your terminal window or an Anaconda Prompt, run:

conda info --envs

The environments list that displays should not show the removed environment.

You anaconda3 enviroments folder might list an empty folder of deleted environment in your anaconda3 installation folder, like:

/opt/anaconda3/envs

回答 3

总共有3种方法可以实现此目的。假设您有一个名为的环境myenv

  1. conda env remove --name myenv-n是的快捷方式--name

  2. conda remove --name myenv --all

  3. 直接删除env文件夹。(不建议)

    # list environments and their locations
    conda env list
    # or
    # conda info --envs
    
    # delete the folder listed
    rm -rf /Users/username/.local/share/conda/envs/myenv

如果您想删除环境而没有提示让您再次检查。使用的-y快捷方式--yes。(对于全局使用,请检查conda中的无提示提示

conda env remove -n myenv -y
conda remove -n myenv --all -y

参考资料

  • conda env --help
  • conda remove --help

There’re 3 ways to achieve this in total. Assuming you have a environment named myenv,

  1. conda env remove --name myenv, -n is shortcut for --name.

  2. conda remove --name myenv --all.

  3. Delete the env folder directly. (Not recommended)

    # list environments and their locations
    conda env list
    # or
    # conda info --envs
    
    # delete the folder listed
    rm -rf /Users/username/.local/share/conda/envs/myenv
    

If you wanna delete the environment without a prompt to let you check again. Use -y, shortcut for --yes. (For global use check silent prompt in conda)

conda env remove -n myenv -y
conda remove -n myenv --all -y

References

  • conda env --help
  • conda remove --help

回答 4

您可以尝试以下操作:打开anaconda命令提示符并键入

conda remove --name myenv --all

这将删除整个环境。

进一步阅读:docs.conda.io>管理环境

You may try the following: Open anaconda command prompt and type

conda remove --name myenv --all

This will remove the entire environment.

Further reading: docs.conda.io > Manage Environments


回答 5

首先,您必须先停用环境,然后再将其删除。您可以使用以下命令删除conda环境

假设您的环境名称为“ sample_env”,则可以使用删除此环境

source deactivate    
conda remove -n sample_env --all

‘–all’将用于删除所有依赖项

First you have to deactivate your environment before removing it. You can remove conda environment by using the following command

Suppose your environment name is “sample_env” , you can remove this environment by using

source deactivate    
conda remove -n sample_env --all

‘–all’ will be used to remove all the dependencies


回答 6

--prefix-p标志创建的环境必须用-p标志(not -n)删除。

例如: conda remove -p </filepath/myenvironment> --all,其中</filepath/myenvironment>用到环境的完整或相对路径代替。

Environments created with the --prefix or -p flag must be removed with the -p flag (not -n).

For example: conda remove -p </filepath/myenvironment> --all, in which </filepath/myenvironment> is substituted with a complete or relative path to the environment.


回答 7

我的环境名称是:test

conda remove -n test --all

My environment name is: test

conda remove -n test --all

回答 8

用于source deactivate在删除环境之前停用它,将ENV_NAME替换为您要删除的环境:

source deactivate
conda env remove -n ENV_NAME

Use source deactivate to deactivate the environment before removing it, replace ENV_NAME with the environment you wish to remove:

source deactivate
conda env remove -n ENV_NAME

回答 9

首先停用环境,然后返回基本环境。从基础上,您应该能够运行命令conda env remove -n <envname>。这会给你消息

Remove all packages in environment C:\Users\<username>\AppData\Local\Continuum\anaconda3\envs\{envname}:

First deactivate the environment and come back to the base environment. From the base, you should be able to run the command conda env remove -n <envname>. This will give you the message

Remove all packages in environment C:\Users\<username>\AppData\Local\Continuum\anaconda3\envs\{envname}:


回答 10

如果您在基地

(base) HP-Compaq-Elite-8300-CMT:~$ 

通过以下方式删除env_name

conda env remove -n env_name

如果您已经在env_name环境中:

(env_name) HP-Compaq-Elite-8300-CMT:~$ 

停用然后通过以下方式删除:

conda deactivate env_name

conda env remove -n env_name

if you are in base:

(base) HP-Compaq-Elite-8300-CMT:~$ 

remove env_name by:

conda env remove -n env_name

if you are already in env_name environment :

(env_name) HP-Compaq-Elite-8300-CMT:~$ 

deactivate then remove by :

conda deactivate env_name

conda env remove -n env_name

回答 11

这为我工作:

conda env remove --name tensorflow

This worked for me:

conda env remove --name tensorflow

回答 12

删除完整的conda环境:

康达删除–name YOUR_CONDA_ENV_NAME-全部

To remove complete conda environment :

conda remove --name YOUR_CONDA_ENV_NAME --all


回答 13

因为您只能停用活动环境,所以conda deactivate既不需要也不接受参数。错误消息在这里非常明确。

只需调用conda停用 https://github.com/conda/conda/issues/7296#issuecomment-389504269

Because you can only deactivate the active environment, so conda deactivate does not need nor accept arguments. The error message is very explicit here.

Just call conda deactivate https://github.com/conda/conda/issues/7296#issuecomment-389504269