如何处理 jupyter 笔记本的 GCP 抢先关闭

How to handle GCP preemptive shutdown for jupyter notebooks

在 Google Cloud Platform 中的抢占式 VM 实例中,可以随时调用强制关闭。它们允许 运行 关闭脚本以避免文件丢失。但是如何使用脚本在我的 jupyter notebook 中引起特定的中断?

Jupyter notebooks 在其后端使用实例 VM,您可以通过 ssh 协议访问它们,就像来自计算引擎的其他实例一样。这意味着任何在计算机引擎实例中运行的脚本都必须与 jupyter notebook 一起运行。

根据你的描述,我了解到你指的是这个 shutdown script。此脚本会在您的实例关闭时保存一个检查点,因此它不会触发关闭命令本身。

many ways 可以从实例内部(脚本)或外部(云 shell、控制台 UI ...)关闭实例。

您能否解释一下您的具体目的,以便我进一步帮助您?

我想到了解决办法

from os import getpid, kill
from time import sleep
import signal
import ipykernel
import psutil


def get_active_kernels():
    active_kernels = []
    pids = psutil.pids()
    my_pid = getpid()

    for pid in pids:
        if pid == my_pid:
            continue
        try:
            p = psutil.Process(pid)
            cmd = p.cmdline()
            for arg in cmd:
                if arg.count('ipykernel'):
                    active_kernels.append(pid)
        except psutil.AccessDenied:
            continue
    return active_kernels

if __name__ == '__main__':
    kernels = get_active_kernels()
    for kernel in kernels:
        kill(kernel, signal.SIGINT)

可以将此代码用作关闭脚本。它调用所有现有 jupyter 内核的键盘中断。因此,可以在 jupyter notebook 中使用一个简单的 try-except 块来排除 KeyboardInterrupt。

try:
    ... #regular code
except KeyboardInterrupt:
    ... #code to save the progress