使用winsw3.0配置 Jupyter Notebook为Windows服务

0. 主要目的

  • 设置jupyter_notebook开机自启动常驻后台
  • 需要自定义配置jupyter的端口ip端口等在局域网访问(给macbook用cuda的机会)
  • 可以自定义jupyter的一些样式修改字体和字体大小等
  • 需要简介方便并且是可以移植的配置

1. 下载winsw3.0

去 github winSW 项目的releases直接下载就好了

2. 配置python环境

比如我是用的miniconda装的环境,然后安装你需要的python包, 这里用Jupyter显然是要安装的,这里不多赘述

3. 编写jupyter配置文件

执行以下命令可以看到默认的jupyter配置文件路径

jupyter notebook --generate-config

C:\Users\<name>\.jupyter\jupyter_notebook_config.py

我这里将整个文件夹位置拷贝到别的盘如F

cp C:\Users\<name>\.jupyter\ F:\winsw\jupyter-conf\

# 大概有如下文件
custom\
nbconfig\
jupyter_notebook_config.json
jupyter_notebook_config.py
migrated

设置jupyter在局域网开放设置端口密码等,在文件jupyter_notebook_config.py后追加

c.NotebookApp.ip = '0.0.0.0'
c.NotebookApp.port = 8889
c.NotebookApp.open_browser = False
c.NotebookApp.password = 'argon2:$argon2id$v=19$m=10240,t=10,p=8$umIQ3OX8ZVwWg+rx4CBZiQ$3nWZKyatZtuuKvzjiWywzTUJkmfnYM81iTP2Cw9lPxM'
c.NotebookApp.notebook_dir =  'F:\JupyterNotebooks'

4. 配置jupyter字体和样式

文件设置在F:\winsw\jupyter-conf\custom\custom.css,以下是我的css样式主要是换字体和字体大小

div.notebook {font-family: Consolas, "Microsoft YaHei Mono", "Microsoft YaHei";}
div.CodeMirror pre {font-family: Consolas, "Microsoft YaHei Mono", "Microsoft YaHei"; font-size: 12pt;}
div.CodeMirror-lines {font-family: Consolas, "Microsoft YaHei Mono", "Microsoft YaHei"!important; font-size: 12pt !important;}
div.output_area pre {font-family: Consolas, "Microsoft YaHei Mono", "Microsoft YaHei"; font-size: 12pt;}
div.input_prompt {font-family: Consolas, "Microsoft YaHei Mono", "Microsoft YaHei"; font-size: 12pt;}
div.out_prompt_overlay {font-family: Consolas, "Microsoft YaHei Mono", "Microsoft YaHei"; font-size: 12pt;}
div.prompt {font-family: Consolas, "Microsoft YaHei Mono", "Microsoft YaHei"; font-size: 12pt;}
span.cm-comment {font-family:  Consolas, "Microsoft YaHei Mono", "Microsoft YaHei" !important; font-style:normal !important;}
code {font-family: Consolas, "Microsoft YaHei Mono", "Microsoft YaHei";}

5. 编写winsw配置文件

具体可以去看winsw的文档,主要是配置环境变量设置成前面拷贝的目录set JUPYTER_CONFIG_DIR=F:\winsw\jupyter-conf,然后服务启动的命令用的python的绝对路径,完整启动为C:\Users\<name>\.conda\envs\torch-env\python.exe -m jupyter notebook

为方便维护把winSW.exe改成winsw-jupyter.exe,配置文件名称winsw-jupyter.xml

<service>
  <id>Jupyter</id>
  <name>Jupyter</name>
  <description>Jupyter Notebook 0.0.0.0:8889</description>
  <env name="JUPYTER_CONFIG_DIR" value="F:\winsw\jupyter-conf"/>
  <executable>C:\Users\xiong\.conda\envs\torch-env\python.exe</executable>
  <arguments>-m jupyter notebook</arguments>
  <onfailure action="restart" delay="10 sec"/>
  <log mode="roll"></log>
</service>

6. 启动服务

文件路径如下
F:\winsw\
    jupyter-conf\
    winsw-jupyter.exe
    winsw-jupyter.xml

# 安装服务
winsw-jupyter.exe install winsw-jupyter.xml

# 启动服务
winsw-jupyter.exe start winsw-jupyter.xml

# 停止服务
winsw-jupyter.exe stop winsw-jupyter.xml

# 重启 ... restart
# 卸载 ... uninstall