""" A script for killing all currently-running Jupyter notebooks, so that launchNotebook can proceed from a clean slate. It will attempt to kill ghost notebooks (when metadata files are left-over but a notebook isn't running, so can't be killed) but if it can't (because they're not there) it will try to just clean up ALL remaining metadata files in the Jupyter run directory. This is probably a bad idea? """ import sys import subprocess import os import os.path __version__ = 1.0 """ Version number for this file. """ # Try to import jupyter_runtime_dir function try: from jupyter_core.paths import jupyter_runtime_dir except ImportError: print("Unable to import jupyter_runtime_dir; won't attempt file cleanup.") jupyter_runtime_dir = None # Exec args list for running jupyter jupyter_exec = [sys.executable, '-m', 'jupyter_core.command'] print(f"Running {jupyter_exec + ['notebook', 'list']}") # Check for already-running servers: result = subprocess.run( jupyter_exec + ['notebook', 'list'], # shell=True, # shell must be False (default) when command is a list capture_output=True, text=True ) if result.stdout: print(result.stdout) # Abort if jupyter is not installed if result.returncode != 0: print( f"Jupyter Notebook server isn't working on your system (return" f" code {result.returncode}). You should ask an instructor for" f" help with this, or if you can, install Anaconda and use that" f" to open the notebook." ) sys.exit(1) if result.stdout and len(result.stdout.splitlines()) > 1: lines = result.stdout.splitlines()[1:] URLs = [line.split('::')[0].strip() for line in lines] print( "One or more notebook servers are running (we will try to stop" " them):" ) cleanup = False for url in URLs: print(' Stopping server at: ' + url) # Extract port from URL try: secondColon = url.index(':', url.index(':') + 1) nextSlash = url.index('/', secondColon + 1) except ValueError: print("URL has unexpected structure; skipping it.") continue port = url[secondColon + 1:nextSlash] # Stop this server result = subprocess.run( jupyter_exec + ['notebook', 'stop', port], capture_output=True, text=True ) if result.returncode != 0: print( f"Notebook at {url} could not be stopped; will attempt to" f" clean up files..." ) print("Stop attempt output was:") print(result.stdout) print("Stop attempt error messages were:") print(result.stderr) cleanup = True if cleanup and jupyter_runtime_dir is not None: print( "Attempting cleanup of ALL remaining server metadata" " files..." ) jRunDir = jupyter_runtime_dir() if not os.path.exists(jRunDir): print("No runtime dir available.") else: runDirFiles = os.listdir(jRunDir) print(f"Found {len(runDirFiles)} file to remove.") for file in runDirFiles: try: os.remove(os.path.join(jRunDir, file)) print(f"Removed file '{file}'") except OSError: print(f"Failed to remove file '{file}'") else: print("No running servers found.")