def test_load_extension(self): app = NotebookApp() stderr = sys.stderr sys.stderr = self.devnull app.initialize(argv=[]) sys.stderr = stderr load_jupyter_server_extension(app)
def test_load_extension(self): app = NotebookApp() stderr = sys.stderr sys.stderr = self.devnull app.initialize() sys.stderr = stderr load_jupyter_server_extension(app)
def pwnbook(_parser, cmd, args): # pragma: no cover """ Start a jupyter notebook with the pwnypack enhanced kernel pre-loaded. """ notebook = NotebookApp(kernel_spec_manager_class=KSM) notebook.initialize(args) notebook.start()
def test_load_ordered(self): app = NotebookApp() app.nbserver_extensions = OrderedDict([('mockextension2',True),('mockextension1',True)]) app.init_server_extensions() assert app.mockII is True, "Mock II should have been loaded" assert app.mockI is True, "Mock I should have been loaded" assert app.mock_shared == 'II', "Mock II should be loaded after Mock I"
def test_load_extension(self): app = NotebookApp() stderr = sys.stderr sys.stderr = self.devnull app.initialize() sys.stderr = stderr web_app = app.web_app prev = len(web_app.handlers) load_jupyter_server_extension(app) assert len(web_app.handlers) > prev
def run_server(target, jupyter_args=None, verbosity=1): RPZKernelManager.rpz_target = target RPZKernelManager.rpz_verbosity = verbosity if not jupyter_args: jupyter_args = [] logger.info("Starting Jupyter notebook") NotebookApp.launch_instance(argv=jupyter_args, kernel_manager_class=RPZMappingKernelManager)
def test_add_handlers(self): app = NotebookApp() stderr = sys.stderr sys.stderr = self.devnull app.initialize() sys.stderr = stderr web_app = app.web_app prev = len(web_app.handlers) add_handlers(web_app, {}) assert len(web_app.handlers) > prev
def dask_setup(scheduler): app = NotebookApp() ip = socket.gethostbyname(socket.gethostname()) app.ip = "0.0.0.0" app.initialize([]) Run.get_context().log( "jupyter-url", "http://" + ip + ":" + str(app.port) + "/?token=" + app.token) Run.get_context().log("jupyter-port", app.port) Run.get_context().log("jupyter-token", app.token) Run.get_context().log("jupyter-ip", ip)
def start(self): # Save current config for the node script. config = dict(baseUrl=self.connection_url, token=self.token) with open('config.json', 'w') as fid: json.dump(config, fid) messaging_pipeline = Queue() messaging_pipeline.put(config) p1 = Process(target=start_node_server, args=(messaging_pipeline, )) p1.start() NotebookApp.start(self)
def nb_app(): from notebook.notebookapp import NotebookApp app = NotebookApp() app.log_level = logging.DEBUG app.ip = '127.0.0.1' app.token = '' app.password = '' app.disable_check_xsrf = True app.initialize() return app.web_app
def test_ignores_tasks_whose_source_is_not_a_file(monkeypatch, capsys, tmp_directory, no_sys_modules_cache): """ Context: jupyter extension only applies to tasks whose source is a script, otherwise it will break, trying to get the source location. This test checks that a SQLUpload (whose source is a data file) task is ignored from the extension """ monkeypatch.setattr(sys, 'argv', ['jupyter']) spec = { 'meta': { 'extract_product': False, 'extract_upstream': False, 'product_default_class': { 'SQLUpload': 'SQLiteRelation' } }, 'clients': { 'SQLUpload': 'db.get_client', 'SQLiteRelation': 'db.get_client' }, 'tasks': [{ 'source': 'some_file.csv', 'name': 'task', 'class': 'SQLUpload', 'product': ['some_table', 'table'] }] } with open('pipeline.yaml', 'w') as f: yaml.dump(spec, f) Path('db.py').write_text(""" from ploomber.clients import SQLAlchemyClient def get_client(): return SQLAlchemyClient('sqlite://') """) Path('file.py').touch() app = NotebookApp() app.initialize() app.contents_manager.get('file.py') out, err = capsys.readouterr() assert 'Traceback' not in err
def nb_app(): sys.argv = ["--port=6005", "--ip=127.0.0.1", "--no-browser", "--debug"] from notebook.notebookapp import NotebookApp app = NotebookApp() app.log_level = logging.DEBUG app.ip = '127.0.0.1' app.token = '' app.password = '' app.disable_check_xsrf = True app.initialize() return app.web_app
def run_notebook(): app = NotebookApp.instance() # Treat IPYTHON_ARGUMENTS from settings ipython_arguments = self.get_ipython_arguments(options) if 'django_extensions.management.notebook_extension' not in ipython_arguments: ipython_arguments.extend([ '--ext', 'django_extensions.management.notebook_extension' ]) # Treat NOTEBOOK_ARGUMENTS from settings notebook_arguments = self.get_notebook_arguments(options) if no_browser and '--no-browser' not in notebook_arguments: notebook_arguments.append('--no-browser') if '--notebook-dir' not in notebook_arguments: notebook_arguments.extend(['--notebook-dir', '.']) # IPython < 3 passes through kernel args from notebook CLI if release.version_info[0] < 3: notebook_arguments.extend(ipython_arguments) app.initialize(notebook_arguments) # IPython >= 3 uses kernelspecs to specify kernel CLI args if release.version_info[0] >= 3: display_name = getattr(settings, 'IPYTHON_KERNEL_DISPLAY_NAME', "Django Shell-Plus") install_kernel_spec(app, display_name, ipython_arguments) app.start()
def n_action(option, opt_str, value, parser): args = [arg for arg in sys.argv[1:] if arg != opt_str] options, args = parser.parse_args(args) sys.argv = ['notebook'] try: # Jupyter/IPython >= 4.0 from notebook.notebookapp import NotebookApp jupyter = True except: # IPython <4.0 from IPython.html.notebookapp import NotebookApp jupyter = False if jupyter: ipython_dir = param.resolve_path('platform/ipython', path_to_file=False) os.environ['IPYTHONDIR'] = ipython_dir config_dir = param.resolve_path('platform/jupyter', path_to_file=False) NotebookApp.config_dir = config_dir else: if options.Profile is None: config_dir = param.resolve_path('platform/ipython/', path_to_file=False) NotebookApp.ipython_dir = config_dir else: NotebookApp.profile = options.Profile if options.IP is not None: NotebookApp.ip = options.IP if options.Port is not None: NotebookApp.port = options.Port NotebookApp().launch_instance() global something_executed something_executed = True
def start_thread(): if 'asyncio' in sys.modules: import asyncio asyncio.set_event_loop(asyncio.new_event_loop()) app = cls.notebook = NotebookApp( port=cls.port, port_retries=0, open_browser=False, config_dir=cls.config_dir, data_dir=cls.data_dir, runtime_dir=cls.runtime_dir, notebook_dir=cls.notebook_dir, base_url=cls.url_prefix, config=config, allow_root=True, token=cls.token, ) # don't register signal handler during tests app.init_signal = lambda: None # clear log handlers and propagate to root for nose to capture it # needs to be redone after initialize, which reconfigures logging app.log.propagate = True app.log.handlers = [] app.initialize(argv=[]) app.log.propagate = True app.log.handlers = [] loop = IOLoop.current() loop.add_callback(started.set) try: app.start() finally: # set the event, so failure to start doesn't cause a hang started.set() app.session_manager.close()
def get_nbextensions_path(): """ Return the nbextensions search path gets the search path for - the current NotebookApp instance or, if we can't instantiate one - the default config used, found by spawning a subprocess """ # Attempt to get the path for the currently-running config, or the default # if one isn't running. # If there's already a non-NotebookApp traitlets app running, e.g. when # we're inside an IPython kernel there's a KernelApp instantiated, then # attempting to get a NotebookApp instance will raise a # MultipleInstanceError. try: return NotebookApp.instance().nbextensions_path except MultipleInstanceError: # So, we spawn a new python process to get paths for the default config cmd = "from {0} import {1}; [print(p) for p in {1}()]".format( get_nbextensions_path.__module__, get_nbextensions_path.__name__) return subprocess.check_output([ sys.executable, '-c', cmd ]).decode(sys.stdout.encoding).split('\n')
def run_notebook(): app = NotebookApp.instance() # Treat IPYTHON_ARGUMENTS from settings ipython_arguments = getattr(settings, 'IPYTHON_ARGUMENTS', []) if 'django_extensions.management.notebook_extension' not in ipython_arguments: ipython_arguments.extend(['--ext', 'django_extensions.management.notebook_extension']) # Treat NOTEBOOK_ARGUMENTS from settings notebook_arguments = getattr(settings, 'NOTEBOOK_ARGUMENTS', []) if no_browser and '--no-browser' not in notebook_arguments: notebook_arguments.append('--no-browser') if '--notebook-dir' not in notebook_arguments: notebook_arguments.extend(['--notebook-dir', '.']) # IPython < 3 passes through kernel args from notebook CLI if release.version_info[0] < 3: notebook_arguments.extend(ipython_arguments) app.initialize(notebook_arguments) # IPython >= 3 uses kernelspecs to specify kernel CLI args if release.version_info[0] >= 3: display_name = getattr(settings, 'IPYTHON_KERNEL_DISPLAY_NAME', "Django Shell-Plus") install_kernel_spec(app, display_name, ipython_arguments) app.start()
def run_notebook(): app = NotebookApp.instance() # Treat IPYTHON_ARGUMENTS from settings ipython_arguments = self.get_ipython_arguments(options) if "django_extensions.management.notebook_extension" not in ipython_arguments: ipython_arguments.extend(["--ext", "django_extensions.management.notebook_extension"]) # Treat NOTEBOOK_ARGUMENTS from settings notebook_arguments = self.get_notebook_arguments(options) if no_browser and "--no-browser" not in notebook_arguments: notebook_arguments.append("--no-browser") if "--notebook-dir" not in notebook_arguments: notebook_arguments.extend(["--notebook-dir", "."]) # IPython < 3 passes through kernel args from notebook CLI if release.version_info[0] < 3: notebook_arguments.extend(ipython_arguments) app.initialize(notebook_arguments) # IPython >= 3 uses kernelspecs to specify kernel CLI args if release.version_info[0] >= 3: display_name = getattr(settings, "IPYTHON_KERNEL_DISPLAY_NAME", "Django Shell-Plus") install_kernel_spec(app, display_name, ipython_arguments) app.start()
def main(): """Run main.""" opt = parse_cmd_line() if opt.serve: # pylint: disable=import-outside-toplevel from imjoy.server import start_server start_server(opt) elif opt.jupyter: sys.argv = sys.argv[:1] sys.argc = 1 # pylint: disable=import-outside-toplevel from notebook.notebookapp import NotebookApp kwargs = { "open_browser": False, "allow_origin": opt.allow_origin, "ip": opt.host, "notebook_dir": opt.workspace, "port": int(opt.port), "tornado_settings": { "headers": { "Access-Control-Allow-Origin": opt.allow_origin, "Content-Security-Policy": opt.content_security_policy, } }, } if not opt.token: if not opt.random_token: opt.token = read_or_generate_token() kwargs["token"] = opt.token else: kwargs["token"] = opt.token if opt.insecure: kwargs["token"] = "" kwargs["disable_check_xsrf"] = True logger.warning( "Running Jupyter notebooks with --insecure flag, " "please do not use it for production." ) app = NotebookApp.instance(**kwargs) app.initialize() if app.port != int(opt.port): print(f"\nWARNING: using a different port: {app.port}.\n") write_token(app.token) app._token_generated = True # pylint: disable=protected-access app.start() else: print( "\nNote: We have migrated the backend of the ImJoy Engine." "You can start the Jupyter backend via`imjoy --jupyter`.\n\n" "Or, you can start the socketio backend server via `imjoy --serve`\n" )
def main(): current_directory = os.path.dirname(os.path.realpath(__file__)) TestPlugin.app = NotebookApp(open_browser=False, notebook_dir=current_directory) TestPlugin.app.initialize() TestPlugin.mock_docker = MagicMock() io_loop = IOLoop.current() io_loop.call_later(1, _run_tests_in_thread) with patch("docker.from_env", return_value=TestPlugin.mock_docker): TestPlugin.app.start()
def run_notebook(): app = NotebookApp.instance() # Treat IPYTHON_ARGUMENTS from settings ipython_arguments = self.get_ipython_arguments(options) if 'django_extensions.management.notebook_extension' not in ipython_arguments: ipython_arguments.extend([ '--ext', 'django_extensions.management.notebook_extension' ]) # Treat NOTEBOOK_ARGUMENTS from settings notebook_arguments = self.get_notebook_arguments(options) if no_browser and '--no-browser' not in notebook_arguments: notebook_arguments.append('--no-browser') if '--notebook-dir' not in notebook_arguments and not any( e.startswith('--notebook-dir=') for e in notebook_arguments): notebook_arguments.extend(['--notebook-dir', '.']) # IPython < 3 passes through kernel args from notebook CLI if release.version_info[0] < 3: notebook_arguments.extend(ipython_arguments) app.initialize(notebook_arguments) # IPython >= 3 uses kernelspecs to specify kernel CLI args if release.version_info[0] >= 3: ksm = app.kernel_spec_manager for kid, ks in self.generate_kernel_specs( app, ipython_arguments).items(): roots = [ os.path.dirname(ks.resource_dir), ksm.user_kernel_dir ] success = False for root in roots: kernel_dir = os.path.join(root, kid) try: if not os.path.exists(kernel_dir): os.makedirs(kernel_dir) with open(os.path.join(kernel_dir, 'kernel.json'), 'w') as f: f.write(ks.to_json()) success = True break except OSError: continue if not success: raise CommandError( "Could not write kernel %r in directories %r" % (kid, roots)) app.start()
def test_merge_config(self): # enabled at sys level mock_sys = self._inject_mock_extension('mockext_sys') # enabled at sys, disabled at user mock_both = self._inject_mock_extension('mockext_both') # enabled at user mock_user = self._inject_mock_extension('mockext_user') # enabled at Python mock_py = self._inject_mock_extension('mockext_py') toggle_serverextension_python('mockext_sys', enabled=True, user=False) toggle_serverextension_python('mockext_user', enabled=True, user=True) toggle_serverextension_python('mockext_both', enabled=True, user=False) toggle_serverextension_python('mockext_both', enabled=False, user=True) app = NotebookApp(nbserver_extensions={'mockext_py': True}) app.init_server_extensions() assert mock_user.loaded assert mock_sys.loaded assert mock_py.loaded assert not mock_both.loaded
def start_notebook(verbose, filename='kpop.ipynb'): try: from notebook.notebookapp import NotebookApp from jupyter_client import KernelManager except ImportError: raise ImportError( 'you must install the notebook module to run this command.\n' '\nRun one of the following commands:\n' ' $ pip3 install notebook\n' ' $ pip3 install kpop[all]' ) file_path = os.path.join(os.getcwd(), filename) if not os.path.exists(file_path): create_default_notebook_file(file_path) sys.argv[:] = ['notebook', 'kpop.ipynb'] NotebookApp.launch_instance( kernel_manager=KernelManager, kernel_name='python', )
def get_server_kwargs(cls, **overrides): kwargs = dict( port=cls.port, port_retries=0, open_browser=False, runtime_dir=cls.jupyter_dirs['server']['runtime'], notebook_dir=cls.jupyter_dirs['server']['notebook'], base_url=cls.url_prefix, config=cls.config, ) # disable auth-by-default, introduced in notebook PR #1831 if 'token' in NotebookApp.class_trait_names(): kwargs['token'] = '' kwargs.update(overrides) return kwargs
def project(self): # 1. configuration option passed explicitly # 2. from notebooks dir # 3. from cwd if self.ballet_yml_path: return Project.from_path(self.ballet_yml_path) path = NotebookApp.instance().notebook_dir with fy.suppress(Exception): return Project.from_path(path) with fy.suppress(Exception): return Project.from_cwd() raise ConfigurationError('Could not detect Ballet project')
def _get_r_executable(): try: # get notebook app from notebook.notebookapp import NotebookApp nbapp = NotebookApp.instance() # get R executable: kernel_name = nbapp.kernel_manager.default_kernel_name if kernel_name: kernel_spec = nbapp.kernel_spec_manager.get_kernel_spec( kernel_name) # nb_conda_kernels has conda env prefix at idx 4 return '{}/bin/R'.format(kernel_spec.argv[4]) except Exception: nbapp.log.warning( 'Error when trying to get R executable from kernel') return 'R'
def run_notebook(no_browser=False, display_name='notebook'): app = NotebookApp.instance() ipython_arguments = [] # Will implement to set specific IPython configs notebook_arguments = [] # Will implement to set specific notebook configs if no_browser is True: notebook_arguments.append('--no-browser') if '--notebook-dir' not in notebook_arguments: notebook_arguments.extend(['--notebook-dir', '.']) install_kernel_spec(app, display_name, ipython_arguments) app.initialize(notebook_arguments) app.start()
def start_notebook(args, l, rc): from notebook.notebookapp import NotebookApp import sys sys.argv = ['ambry'] app = NotebookApp.instance() app._library = l app.contents_manager_class = 'ambry_ui.jupyter.AmbryContentsManager' app.open_browser = not args.no_browser app.ip = args.host if args.port is not None: app.port = int(args.port) app.initialize(None) app.start()
def run_notebook(no_browser=False, display_name='notebook'): app = NotebookApp.instance() ipython_arguments = [ ] # Will implement to set specific IPython configs notebook_arguments = [ ] # Will implement to set specific notebook configs if no_browser is True: notebook_arguments.append('--no-browser') if '--notebook-dir' not in notebook_arguments: notebook_arguments.extend(['--notebook-dir', '.']) install_kernel_spec(app, display_name, ipython_arguments) app.initialize(notebook_arguments) app.start()
def test_basic(self): from notebook.notebookapp import NotebookApp import sys l = self.library() b = l.new_bundle(source='example.com', dataset='test', assignment_class='self') l.commit() sys.argv = ['ambry'] app = NotebookApp.instance() app._library = l app.contents_manager_class = 'ambry_ui.jupyter.AmbryContentsManager' app.initialize(None) cm = app.contents_manager self.assertEqual('example.com', cm.get('')['content'][0]['path']) self.assertEqual('/example.com/test-0.0.1/bundle.yaml', cm.get(b.identity.cache_key)['content'][0]['path'])
def handle(self, arguments): try: from notebook.notebookapp import NotebookApp except ImportError: # pragma: no cover self.parser.error("notebook not found. Please install it") else: extension = "corral.libs.notebook_extension" pipeline = setup.load_pipeline_setup() app = NotebookApp.instance() dir_name = conf.PACKAGE display_name = pipeline.name settings_module = conf.CORRAL_SETTINGS_MODULE ipython_arguments = ['--ext', extension] app.initialize(arguments) self.install_kernel_spec(app, dir_name, display_name, settings_module, ipython_arguments) app.start()
def __call__(self, args): kwargs = {} from notebook.notebookapp import NotebookApp print( "You must choose a password so that others cannot connect to " "your notebook." ) pw = ytcfg.get("yt", "notebook_password") if len(pw) == 0 and not args.no_password: import IPython.lib pw = IPython.lib.passwd() print("If you would like to use this password in the future,") print("place a line like this inside the [yt] section in your") print("yt configuration file at ~/.config/yt/yt.toml") print() print(f"notebook_password = {pw}") print() elif args.no_password: pw = None if args.port != 0: kwargs["port"] = int(args.port) if args.profile is not None: kwargs["profile"] = args.profile if pw is not None: kwargs["password"] = pw app = NotebookApp(open_browser=args.open_browser, **kwargs) app.initialize(argv=[]) print() print("***************************************************************") print() print("The notebook is now live at:") print() print(f" http://127.0.0.1:{app.port}/") print() print("Recall you can create a new SSH tunnel dynamically by pressing") print(f"~C and then typing -L{app.port}:localhost:{app.port}") print("where the first number is the port on your local machine. ") print() print( "If you are using %s on your machine already, try " "-L8889:localhost:%s" % (app.port, app.port) ) print() print("***************************************************************") print() app.start()
def handle(self, arguments): try: from notebook.notebookapp import NotebookApp except ImportError: self.parser.error("notebook not found. Please install it") else: extension = "corral.libs.notebook_extension" pipeline = setup.load_pipeline_setup() app = NotebookApp.instance() dir_name = conf.PACKAGE display_name = pipeline.name settings_module = conf.CORRAL_SETTINGS_MODULE ipython_arguments = ['--ext', extension] app.initialize(arguments) self.install_kernel_spec( app, dir_name, display_name, settings_module, ipython_arguments) app.start()
def launch_notebook(argv=None): """ Launch a Jupyter Notebook, with custom Untitled filenames and a prepopulated first cell with necessary boilerplate code. Notes ----- To populate the first cell, the function `new_notebook` imported in notebook.services.contents needs to be monkey patched. Dirty but functional. Same thing could be achieved with custom.js or a ContentsManager subclass, but this is easier! """ try: import nbformat.v4 as nbf from notebook.notebookapp import NotebookApp from notebook.services.contents import manager from traitlets.config import Config except ImportError: sys.exit("ERROR: Jupyter Notebook not installed in this environment. " "Try with `conda install ipython jupyter notebook`") else: nbf._original_new_notebook = nbf.new_notebook def _prepopulate_nb_patch(): nb = nbf._original_new_notebook() cell = nbf.new_code_cell("# Run this cell to complete Chimera initialization\n" "from pychimera import enable_chimera, enable_chimera_inline, chimera_view\n" "enable_chimera()\nenable_chimera_inline()\nimport chimera") nb['cells'].append(cell) return nb manager.new_notebook = _prepopulate_nb_patch app = NotebookApp() c = Config() c.FileContentsManager.untitled_notebook = "Untitled PyChimera Notebook" app.update_config(c) app.initialize(argv) app.start()
def test_get_labconfig(self): # enabled at sys level self._inject_mock_extension('mockext_sys') install_labextension_python('mockext_sys', user=False) # enabled at sys, disabled at user self._inject_mock_extension('mockext_both') install_labextension_python('mockext_both', user=False) install_labextension_python('mockext_both', user=True) # enabled at user self._inject_mock_extension('mockext_user') install_labextension_python('mockext_user', user=True) enable_labextension_python('mockext_sys', user=False) enable_labextension_python('mockext_user', user=True) enable_labextension_python('mockext_both', user=False) disable_labextension_python('mockext_both', user=True) app = NotebookApp() config = get_labconfig(app).get('labextensions') assert config['mockext_user']['enabled'] assert config['mockext_sys']['enabled'] assert not config['mockext_both']['enabled']
def get_nbextensions_path(): """ Return the nbextensions search path gets the search path for - the current NotebookApp instance or, if we can't instantiate one - the default config used, found by spawning a subprocess """ # Attempt to get the path for the currently-running config, or the default # if one isn't running. # If there's already a non-NotebookApp traitlets app running, e.g. when # we're inside an IPython kernel there's a KernelApp instantiated, then # attempting to get a NotebookApp instance will raise a # MultipleInstanceError. try: return NotebookApp.instance().nbextensions_path except MultipleInstanceError: # So, we spawn a new python process to get paths for the default config cmd = "from {0} import {1}; [print(p) for p in {1}()]".format( get_nbextensions_path.__module__, get_nbextensions_path.__name__) return subprocess.check_output([sys.executable, '-c', cmd]).decode( sys.stdout.encoding).split('\n')
def _log_default(self): """wrap loggers for this application.""" return wrap_logger_handlers(NotebookApp._log_default(self))