Crontab定时执行Jupyter Lab任务

narcissuskid
发布于 2023-08-10 / 197 阅读 / 0 评论 / 0 点赞

Crontab定时执行Jupyter Lab任务

前置条件

问题描述

每天自动运行.ipynb脚本,更新报表

操作步骤

使用 crontab 来定时调度 Jupyter Lab 单元格是一项稍微复杂的任务,因为 Jupyter Lab 并不直接支持命令行操作。但是,我们可以通过一些技巧来模拟定时调度 Jupyter Lab的效果。以下是几种种解决方法:

方法一

  1. 创建执行脚本:
docker exec -i 容器id jupyter nbconvert --to html --execute /home/jovyan/work/test.ipynb #容器中路径
  1. 设置crontab 运行脚本 运行
crontab -e

增加一条记录

0 8 * * * /bin/bash /path/to/run.sh >> /path/to/crontab.log 2>&1 & # 宿主机路径

方法二

  1. 创建定时调度脚本run.py
import nbformat
from nbclient import NotebookClient
import os

path = '/home/jovyan/work/' #容器中路径
filename = 'test.ipynb'
notebook_path = os.path.join(path,filename)
new_path = os.path.join(path,'temp_'+filename)
nb = nbformat.read(notebook_path, as_version=4)
client = NotebookClient(nb)
client.execute()
nbformat.write(nb, new_path)
os.remove(notebook_path)
os.replace(new_path,notebook_path)
  1. 创建执行docker命令的脚本run.sh
docker exec -i 容器id python /home/jovyan/work/run.py #容器中的路径

此处需要注意docker命令参数为-i而不是-it,如果使用-it将提示the input device is not a TTY报错 3. 设置crontab 运行脚本

0 8 * * * /bin/bash /path/to/run.sh >> /path/to/crontab.log 2>&1 & # 宿主机路径

Reference

  1. https://ismailyenigul.medium.com/docker-error-in-crontab-the-input-device-is-not-a-tty-7280cc42cf19
  2. https://nbclient.readthedocs.io/en/latest/client.html
  3. https://mljar.com/blog/schedule-jupyter-notebook/

评论