Created
October 8, 2019 04:25
-
-
Save theTonyHo/1e22d0fd8cc2c2d9e430a00aab97f131 to your computer and use it in GitHub Desktop.
Jupyter Delete All Kernels
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import requests | |
import json | |
import os | |
from IPython.lib import kernel | |
def DeleteAllKernels(excludeCurrentKernel=True): | |
"""This method will delete all kernels of an Jupyter Instance. | |
!!! USE AT YOUR OWN RISKS !!! | |
Args: | |
excludeCurrentKernel (boolean): Specify False to delete current kernel after all other kernels have been deleted. | |
""" | |
def DeleteKernel(kernel_id): | |
if not id: return | |
deleteURL = baseHttp + '/api/kernels/' + kernel_id | |
response = session.delete(deleteURL,headers=headers) | |
print(deleteURL) | |
return response | |
# New requests session | |
session = requests.Session() | |
base = "localhost:8888" | |
baseHttp = "http://{}".format(base) | |
kernelUrl = baseHttp + '/api/kernels' | |
headers = {'Authorization': 'Token JupyterNotebookForEl1Token2'} | |
# Get all jupyter sessions | |
sessionUrl = baseHttp + '/api/sessions' | |
response = session.get(sessionUrl,headers=headers) | |
sessionList = json.loads(response.text) | |
# Get current kernel id | |
# Reference: https://stackoverflow.com/questions/12544056/how-do-i-get-the-current-ipython-notebook-name | |
connection_file_path = kernel.get_connection_file() | |
connection_file = os.path.basename(connection_file_path) | |
current_kernel_id = connection_file.split('kernel-', 1)[1].split('.')[0] | |
for item in sessionList: | |
jKernel = item['kernel'] | |
if jKernel['id'] == current_kernel_id: | |
# Skip current kernel. | |
continue | |
rc = DeleteKernel(jKernel['id']) | |
print(rc) | |
# Delete current kernel if specified. Only when all other kernels have been deleted. | |
if not excludeCurrentKernel: | |
rc = DeleteKernel(current_kernel_id) | |
print(rc) | |
print("Successfully deleted all {} kernels".format(len(sessionList)-excludeCurrentKernel)) | |
return True | |
rc = DeleteAllKernels() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment