How to use the notebook.notebookapp.list_running_servers function in notebook

To help you get started, we’ve selected a few notebook examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github dataflownb / dfkernel / dfkernel / nbtests / test_notebookapp.py View on Github external
def get_servers():
        return list(notebookapp.list_running_servers(nbapp.runtime_dir))
    nbapp.initialize(argv=[])
github allegroai / trains / trains / backend_interface / task / repo / scriptinfo.py View on Github external
def _get_jupyter_notebook_filename(cls):
        if not (sys.argv[0].endswith(os.path.sep+'ipykernel_launcher.py') or
                sys.argv[0].endswith(os.path.join(os.path.sep, 'ipykernel', '__main__.py'))) \
                or len(sys.argv) < 3 or not sys.argv[2].endswith('.json'):
            return None

        # we can safely assume that we can import the notebook package here
        # noinspection PyBroadException
        try:
            from notebook.notebookapp import list_running_servers
            import requests
            current_kernel = sys.argv[2].split(os.path.sep)[-1].replace('kernel-', '').replace('.json', '')
            server_info = next(list_running_servers())
            r = requests.get(
                url=server_info['url'] + 'api/sessions',
                headers={'Authorization': 'token {}'.format(server_info.get('token', '')), })
            r.raise_for_status()
            notebooks = r.json()

            cur_notebook = None
            for n in notebooks:
                if n['kernel']['id'] == current_kernel:
                    cur_notebook = n
                    break

            notebook_path = cur_notebook['notebook'].get('path', '')
            notebook_name = cur_notebook['notebook'].get('name', '')

            is_google_colab = False
github DonJayamanne / pythonVSCode / pythonFiles / datascience / getServerInfo.py View on Github external
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.

try:
    from notebook.notebookapp import list_running_servers
    import json

    server_list = list_running_servers()

    server_info_list = []

    for si in server_list:
        server_info_object = {}
        server_info_object["base_url"] = si['base_url']
        server_info_object["notebook_dir"] = si['notebook_dir']
        server_info_object["hostname"] = si['hostname']
        server_info_object["password"] = si['password']
        server_info_object["pid"] = si['pid']
        server_info_object["port"] = si['port']
        server_info_object["secure"] = si['secure']
        server_info_object["token"] = si['token']
        server_info_object["url"] = si['url']
        server_info_list.append(server_info_object)
github ipython-contrib / jupyter_contrib_nbextensions / src / jupyter_contrib_nbextensions / install.py View on Github external
def notebook_is_running(runtime_dir=None):
    """Return true if a notebook process appears to be running."""
    try:
        return bool(next(list_running_servers(runtime_dir=runtime_dir)))
    except StopIteration:
        return False
github pkgw / pwkit / pwkit / environments / jupyter / __init__.py View on Github external
def get_server_info ():
    servercwd = get_server_cwd ()

    for info in notebookapp.list_running_servers ():
        if Path (info['notebook_dir']) == servercwd:
            return info

    return None
github WorldWideTelescope / pywwt / pywwt / jupyter_server.py View on Github external
"""
    import ipykernel
    import json
    from notebook.notebookapp import list_running_servers
    import re
    import requests

    # First, find our ID.
    kernel_id = re.search(
        'kernel-(.*).json',
        ipykernel.connect.get_connection_file()
    ).group(1)

    # Now, check all of the running servers known on this machine. We have to
    # talk to each server to figure out if it's ours or somebody else's.
    for s in list_running_servers():
        response = requests.get(
            requests.compat.urljoin(s['url'], 'api/sessions'),
            params={'token': s.get('token', '')}
        )

        for n in json.loads(response.text):
            if n['kernel']['id'] == kernel_id:
                return s['base_url']  # Found it!

    raise Exception('cannot locate our notebook server; is this code running in a Jupyter kernel?')
github wandb / client / wandb / jupyter.py View on Github external
def notebook_metadata():
    """Attempts to query jupyter for the path and name of the notebook file"""
    error_message = "Failed to query for notebook name, you can set it manually with the WANDB_NOTEBOOK_NAME environment variable"
    try:
        import ipykernel
        from notebook.notebookapp import list_running_servers
        kernel_id = re.search('kernel-(.*).json', ipykernel.connect.get_connection_file()).group(1)
        servers = list(list_running_servers())  # TODO: sometimes there are invalid JSON files and this blows up
    except Exception:
        logger.error(error_message)
        return {}
    for s in servers:
        try:
            if s['password']:
                raise ValueError("Can't query password protected kernel")
            res = requests.get(urljoin(s['url'], 'api/sessions'), params={'token': s.get('token', '')}).json()
        except (requests.RequestException, ValueError):
            logger.error(error_message)
            return {}
        for nn in res:
            # TODO: wandb/client#400 found a case where res returned an array of strings...
            if isinstance(nn, dict) and nn.get("kernel"):
                if nn['kernel']['id'] == kernel_id:
                    return {"root": s['notebook_dir'], "path": nn['notebook']['path'], "name": nn['notebook']['name']}
github jwkvam / bowtie / bowtie / _magic.py View on Github external
def get_notebook_name() -> str:
    """Return the full path of the jupyter notebook.

    References
    ----------
    https://github.com/jupyter/notebook/issues/1000#issuecomment-359875246

    """
    kernel_id = re.search(  # type: ignore
        'kernel-(.*).json', ipykernel.connect.get_connection_file()
    ).group(1)
    servers = list_running_servers()
    for server in servers:
        response = requests.get(
            urljoin(server['url'], 'api/sessions'), params={'token': server.get('token', '')}
        )
        for session in json.loads(response.text):
            if session['kernel']['id'] == kernel_id:
                relative_path = session['notebook']['path']
                return pjoin(server['notebook_dir'], relative_path)
    raise Exception('Noteboook not found.')