You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过命令行关闭JupyterLab内核?云成本优化场景

命令行关闭JupyterLab内核与终端的可行方案

一、关闭单个/所有Jupyter内核

Jupyter官方提供了内核管理的命令行工具,无需粗暴杀进程或修改文件,就能安全关闭内核。

1. 列出当前运行的内核

先获取所有活跃内核的ID:

jupyter kernel list

输出示例:

Available kernels:
  python3    /usr/local/share/jupyter/kernels/python3
Running kernels:
  12345678-1234-5678-1234-567812345678    tcp://127.0.0.1:8888/api/kernels/12345678-1234-5678-1234-567812345678
  87654321-4321-8765-4321-876543210987    tcp://127.0.0.1:8888/api/kernels/87654321-4321-8765-4321-876543210987

2. 关闭单个内核

通过内核ID执行关闭命令:

jupyter kernel shutdown --kernel 12345678-1234-5678-1234-567812345678

3. 批量关闭所有内核

结合命令行工具提取内核ID,批量关闭:

jupyter kernel list | grep -E '^[0-9a-f-]+' | awk '{print $1}' | xargs -I {} jupyter kernel shutdown --kernel {}

二、关闭JupyterLab终端

JupyterLab的终端可通过REST API管理,步骤如下:

1. 列出所有活跃终端

需提前安装jq解析JSON:

curl -s http://localhost:8888/api/terminals | jq '.[].name'

2. 关闭单个终端

替换{terminal_name}为实际终端名称:

curl -X DELETE http://localhost:8888/api/terminals/{terminal_name}

3. 批量关闭所有终端

curl -s http://localhost:8888/api/terminals | jq -r '.[].name' | xargs -I {} curl -X DELETE http://localhost:8888/api/terminals/{}

三、之前方案失效原因

  • kill -9 {pid}:JupyterLab内置进程监控机制,检测到内核意外终止会自动重启,无法真正关闭内核。
  • 修改ipynb元数据:仅修改本地文件记录,未停止运行中的内核进程,且覆盖文件会丢失未保存内容,风险极高。

四、非工作时段自动执行脚本

将上述命令封装为Shell脚本,配合定时任务(如Linux的cron)自动执行:

示例脚本clean_jupyter_resources.sh:

#!/bin/bash

# 关闭所有内核
jupyter kernel list | grep -E '^[0-9a-f-]+' | awk '{print $1}' | xargs -I {} jupyter kernel shutdown --kernel {}

# 关闭所有终端
curl -s http://localhost:8888/api/terminals | jq -r '.[].name' | xargs -I {} curl -X DELETE http://localhost:8888/api/terminals/{}

添加执行权限:

chmod +x clean_jupyter_resources.sh

通过crontab -e添加定时任务(例:每天22点执行):

0 22 * * * /path/to/clean_jupyter_resources.sh

内容的提问来源于stack exchange,提问作者Ottpocket

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.05 00:43:16