Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
try:
from unittest.mock import patch
except ImportError:
from mock import patch # py2
import nose.tools as nt
from traitlets.tests.utils import check_help_all_output
from jupyter_core.application import NoStart
from ipython_genutils.tempdir import TemporaryDirectory
from traitlets import TraitError
from notebook import notebookapp, __version__
from notebook.auth.security import passwd_check
NotebookApp = notebookapp.NotebookApp
def test_help_output():
"""ipython notebook --help-all works"""
check_help_all_output('notebook')
def test_server_info_file():
td = TemporaryDirectory()
nbapp = NotebookApp(runtime_dir=td.name, log=logging.getLogger())
def get_servers():
return list(notebookapp.list_running_servers(nbapp.runtime_dir))
nbapp.initialize(argv=[])
nbapp.write_server_info_file()
servers = get_servers()
nt.assert_equal(len(servers), 1)
nt.assert_equal(servers[0]['port'], nbapp.port)
# Get whether we should (and can) run as script
scriptFilename = startup_info['scriptFile']
if scriptFilename:
if not os.path.isfile(scriptFilename):
printDirect('Invalid script file: "'+scriptFilename+'"\n')
scriptFilename = None
# Get project path
projectPath = startup_info['projectPath']
if scriptFilename.endswith('.ipynb'):
# Run Jupyter notebook
import notebook.notebookapp
sys.argv = ['jupyter_notebook', scriptFilename]
sys.exit(notebook.notebookapp.main())
elif scriptFilename:
# RUN AS SCRIPT
# Set __file__ (note that __name__ is already '__main__')
self.locals['__file__'] = scriptFilename
# Set command line arguments
sys.argv[:] = []
sys.argv.append(scriptFilename)
sys.argv.extend(shlex.split(startup_info.get('argv', '')))
# Insert script directory to path
theDir = os.path.abspath( os.path.dirname(scriptFilename) )
if theDir not in sys.path:
sys.path.insert(0, theDir)
if projectPath is not None:
sys.path.insert(0,projectPath)
# Go to script dir
def find_best_server(filename):
"""Find the best server to open a notebook with."""
servers = [si for si in notebookapp.list_running_servers()
if filename.startswith(si['notebook_dir'])]
try:
return max(servers, key=lambda si: len(si['notebook_dir']))
except ValueError:
return None
def find_best_server(filename):
servers = [si for si in notebookapp.list_running_servers()
if filename.startswith(si['notebook_dir'])]
try:
return max(servers, key=lambda si: len(si['notebook_dir']))
except ValueError:
return None
def _start_notebook(self, args, cwd, env):
from notebook import notebookapp as app
# Args must not have ['notebook'] in the begining. Drop the `notebook` subcommand when using `jupyter`
args = args[1:] if args[0] == "notebook" else args
self.log.info("Starting notebook with args %s", args)
# When launching notebook always ensure the first argument is `notebook`.
with change_exec_context(args, cwd, env):
app.launch_new_instance()
def _start_notebook(self, args, cwd, env):
from notebook import notebookapp as app
# Args must not have ['notebook'] in the begining. Drop the `notebook` subcommand when using `jupyter`
args = args[1:] if args[0] == "notebook" else args
self.log.info("Starting notebook with args %s", args)
# When launching notebook always ensure the first argument is `notebook`.
with change_exec_context(args, cwd, env):
app.launch_new_instance()
def nbopen(filename):
filename = os.path.abspath(filename)
home_dir = os.path.expanduser('~')
server_inf = find_best_server(filename)
if server_inf is not None:
print("Using existing server at", server_inf['notebook_dir'])
path = os.path.relpath(filename, start=server_inf['notebook_dir'])
if os.sep != '/':
path = path.replace(os.sep, '/')
url = url_path_join(server_inf['url'], 'notebooks', url_escape(path))
na = notebookapp.NotebookApp.instance()
na.load_config_file()
browser = webbrowser.get(na.browser or None)
browser.open(url, new=2)
else:
if filename.startswith(home_dir):
nbdir = home_dir
else:
nbdir = os.path.dirname(filename)
print("Starting new server")
# Hack: we want to override these settings if they're in the config file.
# The application class allows 'command line' config to override config
# loaded afterwards from the config file. So by specifying config, we
# can use this mechanism.
cfg = Config()
cfg.NotebookApp.file_to_run = os.path.abspath(filename)
return self._execute_and_capture_output(self._print_kernel_list)
elif args == ["kernelspec", "--version"]:
return self._execute_and_capture_output(
self._print_kernelspec_version
)
if (
args[0] == "nbconvert"
and self._is_module_installed("nbconvert")
and args[-1] != "--version"
):
return self._execute_and_capture_output(lambda: self._convert(args))
if args[0] == "notebook" and args[1] == "--version":
try:
from notebook import notebookapp as app
return {"stdout": ".".join(list(str(v) for v in app.version_info))}
except Exception:
pass
# kernelspec, nbconvert are subcommands of jupyter.
# python -m jupyter kernelspec, python -m jupyter nbconvert,
# In such cases, even if the modules kernelspec or nbconvert are not installed in the current
# environment, jupyter will find them in current path.
# So if we cannot find the corresponding subcommands, lets revert to subprocess.
self.log.info(
"Exec in DS Daemon with as subprocess, %s with args %s",
module_name,
args,
)
return self._exec_with_subprocess(module_name, args, cwd, env)
else:
self.log.info("check base class stuff")
return super().m_exec_module(module_name, args, cwd, env)
def run_jupyter(jupyter_commands):
app.launch_new_instance(jupyter_commands)