Skip to content

Instantly share code, notes, and snippets.

@jbarratt
Last active August 29, 2015 14:04
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jbarratt/ae8026493fedc79f122b to your computer and use it in GitHub Desktop.
Save jbarratt/ae8026493fedc79f122b to your computer and use it in GitHub Desktop.
nblist
#!/usr/bin/env python
""" A cross-platform (POSIX, at least) tool to list running IPython Notebooks
and their working directories.
This code will be incredibly simpler to write as of IPython 3.0, so
contains numerous workarounds to make it work on 2.x.
Thanks to @takluyver for the suggestions for improvement.
"""
from IPython.core.profiledir import ProfileDir
from IPython.utils.path import get_ipython_dir
from distutils.version import LooseVersion
import IPython
import errno
import os
import io
import json
import re
def check_version():
if LooseVersion(IPython.__version__) >= LooseVersion("3.0.0"):
print "Warning: unnecessary workarounds in play."
print "This code should be upgraded for v3.x"
def check_pid(pid):
""" Returns True if a process is running, False if not.
This is defined in
https://github.com/ipython/ipython/blob/master/IPython/utils/_process_posix.py
but is not yet released.
"""
try:
os.kill(pid, 0)
except OSError as err:
if err.errno == errno.ESRCH:
return False
elif err.errno == errno.EPERM:
# Don't have permission to signal the process - probably means it
# exists
return True
raise
else:
return True
def list_running_servers(profile='default'):
""" Based on the 2.2.0 version of IPython/html/notebookapp.py
Extended to extract the process id from the filename, as it isn't
stored in the JSON until IPython 3.x
Iterate over the server info files of running notebook servers.
Given a profile name, find nbserver-* files in the security directory of
that profile, and yield dicts of their information, each one pertaining to
a currently running notebook server instance.
"""
pd = ProfileDir.find_profile_dir_by_name(get_ipython_dir(), name=profile)
for file in os.listdir(pd.security_dir):
if file.startswith('nbserver-'):
with io.open(os.path.join(pd.security_dir, file),
encoding='utf-8') as f:
info = json.load(f)
# Extract the PID from the filename. As of v3 PID
# is stored in the json so the official list_running_servers
# will work just fine and we won't need this hack.
info['pid'] = int(re.findall(r'\d+', file)[0])
yield(info)
if __name__ == "__main__":
check_version()
for server in list_running_servers():
if check_pid(server['pid']):
print "{} | {}".format(server['url'], server['notebook_dir'])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment