nbconvert 转化成HTML后无法显示滚动条

nbconvert don't show scrollbar for long output

有时使用notebook时会结果输出会很长, notebook会使用滚动条使结果显示在有限空间内, 从而使得notebook界面更整洁.

然而, 当使用nbconvert进行转化后, 生成的HTML缺失了滚动条! 因此结果部分可能很长很长.

解决办法是, 使用一个trick, 利用custom.css载入用户定义的样式. 在转化时, nbconvert会将~/.jupyter/custom/custom.css里的内容以<style>....</style>的形式插入到HTML中. 默认的custom.css样式是:

/*This file contains any manual css for this page that needs to override the global styles.
This is only required when different pages style the same element differently. This is just
a hack to deal with our current css styles and no new styling should be added in this file.*/

#ipython-main-app {
    position: relative;
}
#jupyter-main-app {
    position: relative;
}

这个trick是我在比较jupyterthemes无法正常输出样式到html时发现的, nbconvert会将里面的自定义css加入到html中, 而实际上生成的html对象的名称属性却对不上, 因此不能正确显示jupyterthemes的样式. 而jupyterthemes做了啥? 就是更改了~/.jupyter/custom/custom.css. 使用jt -r恢复默认主题时, 就会恢复上面的样式.

因此可以利用这个细节, 做个trick: 备份原来的custom.css, 根据上面的默认样式, 再加入滚动条控制输出就行了. 查看了输出结果的类型, 可以利用output_subarea来控制:

/*This file contains any manual css for this page that needs to override the global styles.
This is only required when different pages style the same element differently. This is just
a hack to deal with our current css styles and no new styling should be added in this file.*/

#ipython-main-app {
    position: relative;
}
#jupyter-main-app {
    position: relative;
}
div.output_subarea {
  max-height: 600px;
  overflow: scroll;
}

核心的步骤是:

#! /bin/bash
# Name: nb2html.sh
# By Hom on 2019.2.03

# backup origin custom.css
mv ~/.jupyter/custom/custom.css ~/.jupyter/custom/custom.css.bak

# Create new default css with scrollbar
echo "/*This file contains any manual css for this page that needs to override the global styles.
This is only required when different pages style the same element differently. This is just
a hack to deal with our current css styles and no new styling should be added in this file.*/

#ipython-main-app {
    position: relative;
}
#jupyter-main-app {
    position: relative;
}
div.output_subarea {
  max-height: 600px;
  overflow: scroll;
}" > ~/.jupyter/custom/custom.css

#### perform nbconvert
if [ -z $2 ]; then
    jupyter nbconvert --to html --ExtractOutputPreprocessor.enabled=False $1
elif [ $2 = 'toc' ];then
    jupyter nbconvert --to html_toc --ExtractOutputPreprocessor.enabled=False $1
elif [ $2 = 'embed' ];then
    jupyter nbconvert --to html_embed --ExtractOutputPreprocessor.enabled=False $1
else
    jupyter nbconvert --to html --ExtractOutputPreprocessor.enabled=False $1
fi

# Restore custom css pattern
mv ~/.jupyter/custom/custom.css.bak ~/.jupyter/custom/custom.css

使用时:

./nb2html.sh file.ipynb        # Convert to normal html
./nb2html.sh file.ipynb toc    # Convert to html with toc
./nb2html.sh file.ipynb embed  # Convert to embed HTML

Enjoy! Hope help!

猜你喜欢

转载自blog.csdn.net/weixin_34152820/article/details/87015222
今日推荐