コード例 #1
0
def notebookPath(verbose=False):
    """Returns the absolute path of the Notebook.
  """
    from jupyter_server import serverapp as app
    import json
    import os
    import urllib
    connection_file = os.path.basename(
        slicer.modules.jupyterkernel.connectionFile)
    kernel_id = connection_file.split('-', 1)[1].split('.')[0]
    for srv in app.list_running_servers():
        try:
            if srv['token'] == '' and not srv[
                    'password']:  # No token and no password, ahem...
                req = urllib.request.urlopen(srv['url'] + 'api/sessions')
            else:
                req = urllib.request.urlopen(srv['url'] +
                                             'api/sessions?token=' +
                                             srv['token'])
            sessions = json.load(req)
            for sess in sessions:
                if sess['kernel']['id'] == kernel_id:
                    return os.path.join(srv['root_dir'],
                                        sess['notebook']['path'])
        except:
            pass  # There may be stale entries in the runtime directory
    return None
コード例 #2
0
def test_server_info_file(tmp_path, configurable_serverapp):
    app = configurable_serverapp(log=logging.getLogger())

    app.write_server_info_file()
    servers = list(list_running_servers(app.runtime_dir))

    assert len(servers) == 1
    sinfo = servers[0]

    assert sinfo['port'] == app.port
    assert sinfo['url'] == app.connection_url
    assert sinfo['version'] == app.version

    app.remove_server_info_file()

    assert list(list_running_servers(app.runtime_dir)) == []
    app.remove_server_info_file
コード例 #3
0
def my_jupyter_server(verbose=False, jupyter_parent_pid=None):
    servers = []
    imported_notebookapp = imported_serverapp = False
    try:
        from jupyter_server import serverapp
        servers += serverapp.list_running_servers()
        imported_serverapp = True
    except ImportError:
        pass
    try:
        from notebook import notebookapp
        imported_notebookapp = True
        servers += notebookapp.list_running_servers()
    except ImportError:
        pass
    if not len(servers):
        if verbose:
            import warnings
            warnings.warn(
                f"no running jupyter server found - imported jupyter_server: {imported_serverapp} notebook: {imported_notebookapp}"
            )
        return None
    server_pid = os.getenv('JPY_PARENT_PID', jupyter_parent_pid)
    if server_pid is None:
        if len(servers) > 1:
            pass
        jpy = servers[0]
    else:
        for s in servers:
            if str(s['pid']) == server_pid:
                jpy = s
                break
        else:
            # no matching pid found...
            if verbose:
                print('no matching jupyter server found!')
            jpy = servers[0]
    if jpy is None:
        return None
    return dict(
        url=jpy['url'],
        params="token=" + jpy['token'],
        headers={'Authorization': 'token ' + jpy['token']},
    )
コード例 #4
0
def test_list_running_servers(serverapp, app):
    servers = list(list_running_servers(serverapp.runtime_dir))
    assert len(servers) >= 1
コード例 #5
0
def load_ipython_extension(ipython):
    """
    Any module file that define a function named `load_ipython_extension`
    can be loaded via `%load_ext module.path` or be configured to be
    autoloaded by IPython at startup time.
    """
    # You can register the class itself without instantiating it.
    # IPython will call the default constructor on it.

    # https://gist.github.com/mbdevpl/f97205b73610dd30254652e7817f99cb
    connection_file_path = get_connection_file()
    connection_file = os.path.basename(connection_file_path)
    kernel_id = connection_file.split('-', 1)[1].split('.')[0]
    config_files = {'linux':  "/.local/share/nb-agent/runtime.json",
                    'darwin': "/Library/nb-agent/runtime.json",
                    'windows': "/.local/share/nb-agent/runtime.json"}  # I am guessing!

    config_file = str(Path.home()) + config_files[sys.platform]
    with open(config_file) as json_file:
        data = json.load(json_file)
        port = data['magic-server-port']
        jupyter_port = data['jupyter-port']

    ipynb_filename = 'unknown'
    last_active = 'unknown'
    servers = serverapp.list_running_servers()  # for 3.0.9 2021-03-04
    prefix = 'http://127.0.0.1:%s/api/sessions?token=' % (jupyter_port,)
    for svr in servers:
        response = urllib.request.urlopen(prefix + svr['token'])
        sessions = json.loads(response.read().decode())
        for sess in sessions:
            if sess['kernel']['id'] == kernel_id:
                session_id = sess['id']
                ipynb_filename = (sess['notebook']['path'])
                last_active = (sess['kernel']['last_activity'])
                break

    gw = NBAgateway()
    gw.start_server()
    ipython.push({'nba_gateway': gw})  # Not sure that this is needed!

    ctx = zmq.Context()
    sock = ctx.socket(zmq.REQ)
    sock.connect('tcp://localhost:' + str(port))
    try:
        msg = {'action': 'notify',
               'session-id': session_id,
               'nba-gateway-port': gw.port,
               'dir': os.getcwd(),
               'ipynb-file': ipynb_filename,
               'last-active': last_active}
        msg_str = json.dumps(msg)
        sock.send_string(msg_str)
        print('MiniZinc Notebook Agent Communicator version %s'
              % (__version__,))
        print('This session (%s) connected to nb-agent at port %s.' % (session_id, port))
        print(json.loads(sock.recv()))

    except KeyError:
        print('''Not able to communicate with nb-agent.''')

    magics = MznbMagics(ipython, port, session_id)
    ipython.register_magics(magics)
コード例 #6
0
 def get_servers():
     return list(serverapp.list_running_servers(svapp.runtime_dir))
コード例 #7
0
 def test_list_running_servers(self):
     servers = list(serverapp.list_running_servers())
     assert len(servers) >= 1
     assert self.port in {info['port'] for info in servers}