Jupyter notebook的配置

前言 本文介绍jupyter notebook的安装配置过程和实用技巧。 jupyter.readthedocs教程

1 安装与配置

1.1 安装 jupyter

1
2
3
conda install jupyter
# pip install -i https://pypi.tuna.tsinghua.edu.cn/simple jupyter
# pip install jupyter -y

1.2 修改配置文件

  • 生成配置文件
1
2
jupyter notebook --generate-config
vim ~/.jupyter/jupyter_notebook_config.py
  • 修改配置文件内容
1
2
3
4
c.NotebookApp.ip = '0.0.0.0'
c.NotebookApp.port = 8018
# 设置密码
c.NotebookApp.password = u'sha1:bcd259ccf...your hashed password here'

Tip: 利用ipython 生成密码

1
2
3
4
5
6
> In [1]: from IPython.lib import passwd
> In [2]: passwd()
> Enter password:
> Verify password:
> Out[2]: 'sha1:67xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
>

我选用的是password密码登陆jupyter的方案,其他的密码登陆方案见 link

新的方法 from notebook.auth import passwd; passwd()

安装 jupyter-lab

1
2
3
4
5
6
7
8
9
jupyter-lab --generate-config

vim ~/.jupyter/jupyter_lab_config.py

# 允许局域网访问
c.ServerApp.ip = '*'

# 使用 生成密码from jupyter_server.auth import passwd; passwd()
c.ServerApp.password = ''

1.3 安装插件管理

jupyter_contrib_nbextensions 为 jupyter notebook 扩展插件管理器,下面简称nbextensions。

nbextensions的github repo nbextensions的教程nbextensions_manual_readthedocs

1
2
3
4
5
6
7
8
9
# 用conda安装
conda install jupyter
conda install -c conda-forge jupyter_contrib_nbextensions

# pip安装
pip install jupyter_contrib_nbextensions

# 使能
jupyter contrib nbextension install

我启用的一些插件

plugins
Table of Contents (2)
Freeze比较好的一个插件,可以用来冻住cell
nbTranslate这个插件利用Google翻译cell很好用support languages
ExecuteTime显示执行时间
Ruler代码标尺
Autopep8代码美化
Scratchpad代码测试

其他花样的配置

https://zhuanlan.zhihu.com/p/74950682

1.4 conda环境的设置

jupyter使用Anaconda miniconda环境需要安装的组件。 conda repo

1
2
3
4
5
# 创建虚拟环境
conda create -n env_name python=3.6

# conda虚拟核组件 切换kernel
conda install nb_conda_kernels

1.5 解决界面中英文混杂

image-20200413125705473

如图,jupyter 界面中中英文混杂,解决方法为将界面文字中文切换成英文。

原理:让jupyter就找不到他的中文配置文件夹。

找到notebook的汉化文件夹的路径,比如~/miniconda3/lib/python3.6/site-packages/notebook/i18n/zh_CN。将其重命名如加个下划线作为后缀zh_CN_old,重启jupyter就行了。

为了方便,我作了个脚本自动找notebook/i18n/zh_CN位置并改名此文件夹,如下。

1
2
3
4
5
6
7
8
9
10
11
import shutil
from distutils.sysconfig import get_python_lib
# 获取site-package包的位置
path_zh=get_python_lib()+'/notebook/i18n/zh_CN'
path_zh_old=get_python_lib()+'/notebook/i18n/zh_CN_old'

# 将 notebook/i18n/zh_CN 改为 notebook/i18n/zh_CN_old
shutil.move(path_zh,path_zh_old)

# 返回中文
# shutil.move(path_zh_old,path_zh)

重启jupyter就行了, 这样jupyter就找不到这个中文配置,返回中文改回去就行了[1]

2 使用的技巧

2.1 快捷键


在非激活状态即是蓝颜色的边框内容
Ainsert cell above
Binsert cell below
H查看帮助
⌃↩(ctrl + enter)run selected cells

2.2 显示图片 视频 音频

主要是画图、显示视频和音频的方法。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# 图片
%%HTML
<img src="xxx.jpg" alt="title" />

# 视频
%%HTML
<video width="330" height="150" controls>
<source src="out_all.mp4" type="video/mp4">
</video>

# 语音
%%HTML
<audio src="out.wav" controls="controls">
Your browser does not support the audio element.
</audio>

# html t是html的字符串
from IPython.core.display import HTML
HTML(str(t))

2.3 其他技巧

修复视频文件

1
2
3
4
5
6
7
def fix_use_ffmpeg(in_name, out_name,message=""):
import os
if os.path.isfile(out_name):
os.remove(out_name)
cmd = 'ffmpeg -i %s %s' % (in_name, out_name)
log_lines = os.popen(cmd).readlines()
print(message,"ok")

加载自己的模块文件

出于性能考虑,每个模块在每个解释器会话中只导入一遍。因此,如果你修改了你的模块,需要重启解释器;或者,如果你就是想交互式的测试这么一个模块,可以用 imp.reload() 重新加载,例如 import imp; imp.reload(modulename)

导出pdf支持中文

Jupyter Notebook 输出PDF中文支持 link

1
2
3
4
5
cd /usr/local/lib/python3.6/site-packages/nbconvert/templates/latex

# 在里面的模版中添加,前提是安装好了texlive
% add
\usepackage{ctex}

ipynb2pdf

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
#!/usr/bin/env python3
"""
Current version of Jupyter doesn't support pdf exporting when it comes to
russian language in the document. To fix this, current script has born.
It requires nbconvert as long as jupyter to be installed.
Author: Sergey Ivanychev
Email: sergeyivanychev@gmail.com
Revision: 1
"""

import sys
import os
import subprocess

FORMAT = ".ipynb"
"""
TODO: What if user has ___o.tex in current folder?
"""
TEMP_TEX = "___o.tex"
TEMP_FOLDER = "/tmp"
TRASH_EXTENSIONS = [".aux", ".out", ".log"]
OLD1 = r"\usepackage[utf8x]{inputenc}"
NEW1 = r"""
\usepackage[utf8x]{inputenc}
\usepackage{ctex}
"""
REPLACE = [(OLD1, NEW1)]
HELP = """
This script is aimed at correctly converting .ipynb to .pdf files.
You may use it via
# ipynb2pdf Solution.ipynb
To get .pdf in the same directory
"""

def check_args(argv):
if (len(argv) > 2):
print("Please, type .ipynb filename as argument")
return -1
if (len(argv) == 1):
print(HELP)
return -1
script, filename = argv
if not is_ipynb(filename):
print("Please, type .ipynb filename as argument")
return -1

def remove_extention(string, extention):
"""
Removes argumented extention from the end of the string
"""
if extention[0] != '.':
extention = "." + extention
if string.endswith(extention):
string = string[0:-len(extention)]
return string

def is_ipynb(filename):
if not filename.endswith(".ipynb"):
return False
return True

def tex2pdf(filename, desired_name):
"""
Converts filename (which is tex document) to desired_name (which is pdf)
leaving no trash in current folder
"""
base = remove_extention(filename, "tex")
output = base + ".pdf"
ret = subprocess.call("xelatex %s" % filename ,
shell=True, stdout=subprocess.PIPE)
for ext in TRASH_EXTENSIONS:
os.unlink(base + ext)
os.rename(output, desired_name)
return ret

def main(argv):
if check_args(argv) == -1:
return -1
script, filename = argv
ret = subprocess.call("jupyter nbconvert %s --to latex --output %s" %
(filename, TEMP_TEX), shell=True,
stdout=subprocess.PIPE)
if (ret != 0):
print("ret = %d" % ret)
os.unlink(TEMP_TEX)
print("Converting to LaTeX failed. Return code: %d" % ret)
return -1
tex_file = open(TEMP_TEX, "r")
tex = tex_file.read()
for old, new in REPLACE:
tex = tex.replace(old, new)
tex_file.close()
os.unlink(TEMP_TEX)
tex_file = open(TEMP_TEX, "w+")
tex_file.write(tex)
tex_file.close()
ret = tex2pdf(TEMP_TEX, remove_extention(filename, ".ipynb") + ".pdf")
tex_file.close()
os.unlink(TEMP_TEX)
print(remove_extention(filename, ".ipynb") + ".pdf - DONE")
return 0

if __name__ == "__main__":
exit(main(sys.argv))

  1. https://www.zhihu.com/question/302814218/answer/1029684239 ↩︎

0%