前言 本文介绍jupyter notebook的安装配置过程和实用技巧。 jupyter.readthedocs教程
1 安装与配置
1.1 安装 jupyter
conda install jupyter
# pip install -i https://pypi.tuna.tsinghua.edu.cn/simple jupyter
# pip install jupyter -y
1.2 修改配置文件
- 生成配置文件
jupyter notebook --generate-config
vim ~/.jupyter/jupyter_notebook_config.py
- 修改配置文件内容
c.NotebookApp.ip = '0.0.0.0'
c.NotebookApp.port = 8018
# 设置密码
c.NotebookApp.password = u'sha1:bcd259ccf...your hashed password here'
Tip: 利用ipython 生成密码
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
jupyter-lab --generate-config
vim ~/.jupyter/jupyter_lab_config.py
# 允许局域网访问
c.ServerApp.ip = '*'
# 使用 生成密码from jupyter_server.auth import passwd; passwd()
c.ServerApp.password = ''
安装低版本jupyter
python3 -m venv xxx
IPython==8.12.0
notebook==6.4.12
jupyter-server==1.13.4
traitlets==5.9.0
# 安装依赖插件
pip install jupyter_contrib_nbextensions jupyter_nbextensions_configurator
# 激活扩展管理器
jupyter contrib nbextension install --user
jupyter nbextensions_configurator enable --user
1.3 安装插件管理
jupyter_contrib_nbextensions 为 jupyter notebook 扩展插件管理器,下面简称nbextensions。
nbextensions的github repo nbextensions的教程nbextensions_manual_readthedocs
# 用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
# 创建虚拟环境
conda create -n env_name python=3.6
# conda虚拟核组件 切换kernel
conda install nb_conda_kernels
1.5 解决界面中英文混杂

如图,jupyter 界面中中英文混杂,解决方法为将界面文字中文切换成英文。
原理:让jupyter就找不到他的中文配置文件夹。
找到notebook的汉化文件夹的路径,比如~/miniconda3/lib/python3.6/site-packages/notebook/i18n/zh_CN。将其重命名如加个下划线作为后缀zh_CN_old,重启jupyter就行了。
为了方便,我作了个脚本自动找notebook/i18n/zh_CN位置并改名此文件夹,如下。
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 快捷键
| 在非激活状态即是蓝颜色的边框 | 内容 |
|---|---|
| A | insert cell above |
| B | insert cell below |
| H | 查看帮助 |
| ⌃↩(ctrl + enter) | run selected cells |
2.2 显示图片 视频 音频
主要是画图、显示视频和音频的方法。
# 图片
%%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 其他技巧
修复视频文件
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
cd /usr/local/lib/python3.6/site-packages/nbconvert/templates/latex
# 在里面的模版中添加,前提是安装好了texlive
% add
\usepackage{ctex}
ipynb2pdf
#!/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))