def script_post_save(model, os_path, contents_manager, **kwargs): """convert notebooks to Python script after save with nbconvert replaces `ipython notebook --script` """ from nbconvert.exporters.script import ScriptExporter from nbconvert.exporters.html import HTMLExporter if model['type'] != 'notebook': return global _script_exporter if _script_exporter is None: _script_exporter = ScriptExporter(parent=contents_manager) log = contents_manager.log global _html_exporter if _html_exporter is None: _html_exporter = HTMLExporter(parent=contents_manager) log = contents_manager.log # save .py file base, ext = os.path.splitext(os_path) script, resources = _script_exporter.from_filename(os_path) script_fname = base + resources.get('output_extension', '.txt') log.info("Saving script /%s", to_api_path(script_fname, contents_manager.root_dir)) with io.open(script_fname, 'w', encoding='utf-8') as f: f.write(script) # save html base, ext = os.path.splitext(os_path) script, resources = _html_exporter.from_filename(os_path) script_fname = base + resources.get('output_extension', '.txt') log.info("Saving html /%s", to_api_path(script_fname, contents_manager.root_dir)) with io.open(script_fname, 'w', encoding='utf-8') as f: f.write(script)
def script_post_save(model, os_path, contents_manager, **kwargs): if (model['type'] != 'notebook'): return # auto save .py global _script_exporter if _script_exporter is None: _script_exporter = ScriptExporter(parent=contents_manager) log_py = contents_manager.log base, ext = os.path.splitext(os_path) script, resources = _script_exporter.from_filename(os_path) script_fname = base + resources.get('output_extension', '.txt') log_py.info("Saving script /%s", to_api_path(script_fname, contents_manager.root_dir)) with io.open(script_fname, 'w', encoding='utf-8') as f: f.write(script) # auto save html global _html_exporter if _html_exporter is None: _html_exporter = HTMLExporter(parent=contents_manager) log_h5 = contents_manager.log base, ext = os.path.splitext(os_path) script, resources = _html_exporter.from_filename(os_path) script_fname = base + resources.get('output_extension', '.txt') log_h5.info("Saving html /%s", to_api_path(script_fname, contents_manager.root_dir)) with io.open(script_fname, 'w', encoding='utf-8') as f: f.write(script)
def script_post_save(model, os_path, contents_manager, **kwargs): import os from notebook.utils import to_api_path import io """convert notebooks to Python script after save with nbconvert replaces `ipython notebook --script` """ from nbconvert.exporters.python import PythonExporter from nbconvert.exporters.html import HTMLExporter if model['type'] != 'notebook': return global _python_exporter #if _python_exporter is None: _python_exporter = PythonExporter(parent=contents_manager) log = contents_manager.log global _html_exporter #if _html_exporter is None: _html_exporter = HTMLExporter(parent=contents_manager) log = contents_manager.log # save .py file base, ext = os.path.splitext(os_path) script, resources = _python_exporter.from_filename(os_path) script_fname = base + '.py' log.info("Saving python /%s", to_api_path(script_fname, contents_manager.root_dir)) with io.open(script_fname, 'w', encoding='utf-8') as f: f.write(script) import subprocess subprocess.Popen("/bin/mv {0} {0}.tmp".format(script_fname), shell=True) subprocess.Popen( "cat {0}.tmp | grep -v get_ipython | grep -v '# In\[' | cat -s > {0}". format(script_fname), shell=True) subprocess.Popen("rm {0}.tmp".format(script_fname), shell=True) # save html base, ext = os.path.splitext(os_path) script, resources = _html_exporter.from_filename(os_path) script_fname = base + resources.get('output_extension', '.html') log.info("Saving html /%s", to_api_path(script_fname, contents_manager.root_dir)) with io.open(script_fname, 'w', encoding='utf-8') as f: f.write(script)
def script_post_save(model, os_path, contents_manager, **kwargs): MIRROR_DIRECTORY = "code_mirrors" from nbconvert.exporters.script import ScriptExporter if model['type'] != 'notebook': return global _script_exporter if _script_exporter is None: _script_exporter = ScriptExporter(parent=contents_manager) log = contents_manager.log base, ext = os.path.splitext(os_path) index_filename_start = base.rfind('/') + 1 base = base[:index_filename_start] + 'code_mirrors/' + base[ index_filename_start:] # Save to subdirectory py_fname = base + '.py' script, resources = _script_exporter.from_filename(os_path) script_fname = base + resources.get('output_extension', '.txt') log.info("Saving script /%s", to_api_path(script_fname, contents_manager.root_dir)) with io.open(os.path.join(MIRROR_DIRECTORY, script_fname), 'w', encoding='utf-8') as f: for line in script.split('\n'): if "# In" in line: continue f.write(line + '\n')
def perm_to_403(self, os_path=''): """context manager for turning permission errors into 403.""" try: yield except (OSError, IOError) as e: if e.errno in {errno.EPERM, errno.EACCES}: # make 403 error message without root prefix # this may not work perfectly on unicode paths on Python 2, # but nobody should be doing that anyway. if not os_path: os_path = str_to_unicode(e.filename or 'unknown file') path = to_api_path(os_path, root=self.root_dir) # iOS: better error message import sys if (sys.platform == "darwin" and os.uname().machine.startswith("iP")): raise HTTPError( 403, u'Permission denied: %s (maybe you need to grand permission on the folder)' % path) from e else: raise HTTPError(403, u'Permission denied: %s' % path) from e else: raise
def script_post_save(model, os_path, contents_manager, **kwargs): """convert notebooks to Python script after save with nbconvert replaces `ipython notebook --script` http://jupyter-notebook.readthedocs.io/en/latest/extending/savehooks.html """ from nbconvert.exporters.script import ScriptExporter if model['type'] != 'notebook': return global _script_exporter if _script_exporter is None: _script_exporter = ScriptExporter(parent=contents_manager) log = contents_manager.log base, ext = os.path.splitext(os_path) py_fname = base + '.py' script, resources = _script_exporter.from_filename(os_path) script_fname = base + resources.get('output_extension', '.txt') log.info("Saving script /%s", to_api_path(script_fname, contents_manager.root_dir)) with io.open(script_fname, 'w', encoding='utf-8') as f: f.write(script)
def _post_save_script(model, os_path, contents_manager, **kwargs): """convert notebooks to Python script after save with nbconvert replaces `jupyter notebook --script` """ from nbconvert.exporters.script import ScriptExporter warnings.warn( "`_post_save_script` is deprecated and will be removed in Notebook 5.0", DeprecationWarning) if model['type'] != 'notebook': return global _script_exporter if _script_exporter is None: _script_exporter = ScriptExporter(parent=contents_manager) log = contents_manager.log base, ext = os.path.splitext(os_path) script, resources = _script_exporter.from_filename(os_path) script_fname = base + resources.get('output_extension', '.txt') log.info("Saving script /%s", to_api_path(script_fname, contents_manager.root_dir)) with io.open(script_fname, 'w', encoding='utf-8') as f: f.write(script)
def script_post_save(model, os_path, contents_manager, **kwargs): """convert notebooks to Python script after save with nbconvert replaces `ipython notebook --script` """ from nbconvert.exporters.script import ScriptExporter if model['type'] != 'notebook': return global _script_exporter if _script_exporter is None: _script_exporter = ScriptExporter(parent=contents_manager) log = contents_manager.log base, ext = os.path.splitext(os_path) py_fname = base + '.py' script, resources = _script_exporter.from_filename(os_path) script_fname = base + resources.get('output_extension', '.txt') log.info("Saving script /%s", to_api_path(script_fname, contents_manager.root_dir)) input_prompt = re.compile(r'^# In\[((\d+)|(\s+))\]:$') script = "\n".join([l for l in script.split('\n') if not input_prompt.match(l)]) with io.open(script_fname, 'w', encoding='utf-8') as f: f.write(script)
def script_post_save(model, os_path, contents_manager, **kwargs): """ Converts notebooks to Python script on save. See https://jupyter-notebook.readthedocs.io/en/stable/extending/savehooks.html for more information. """ from nbconvert.exporters.script import ScriptExporter if model['type'] != 'notebook': return global _script_exporter if _script_exporter is None: _script_exporter = ScriptExporter(parent=contents_manager) log = contents_manager.log base, ext = os.path.splitext(os.path.realpath(os_path)) script, resources = _script_exporter.from_filename(os_path) script_fname = base + resources.get('output_extension', '.txt') log.info("Saving script /%s", to_api_path(script_fname, contents_manager.root_dir)) with io.open(script_fname, 'w', encoding='utf-8') as f: f.write(script)
def save_as_markdown_and_script_post_save(model, os_path, contents_manager, **kwargs): from nbconvert.exporters.markdown import MarkdownExporter from nbconvert.exporters.script import ScriptExporter if model['type'] != 'notebook': return log = contents_manager.log base, ext = os.path.splitext(os_path) from subprocess import call markdown_cmd = "jupyter nbconvert --to markdown" call(markdown_cmd.split() + [os_path]) global _script_exporter if _script_exporter is None: _script_exporter = ScriptExporter(parent=contents_manager) script, script_resources = _script_exporter.from_filename(os_path) script_fname = base + script_resources.get('output_extension', '.py') log.info("Saving script /%s", to_api_path(script_fname, contents_manager.root_dir)) with io.open(script_fname, 'w', encoding='utf-8') as f: script = re.sub(r"# In\[(\d+| )\]:\n", "", script) f.write(script)
def export_script(exporter, model, os_path, contents_manager, **kwargs): """convert notebooks to Python script after save with nbconvert replaces `ipython notebook --script` """ base, ext = os.path.splitext(os_path) script, resources = exporter.from_filename(os_path) script_fname = base + resources.get('output_extension', '.txt') log = contents_manager.log log.info("Saving script /%s", to_api_path(script_fname, contents_manager.root_dir)) with io.open(script_fname, 'w', encoding='utf-8') as f: f.write(script)
def export_script(exporter, model, os_path, contents_manager, **kwargs): """convert notebooks to Python script after save with nbconvert replaces `ipython notebook --script` """ base, ext = os.path.splitext(os_path) script, resources = exporter.from_filename(os_path) script_fname = base + resources.get('output_extension', '.txt') script_repopath = to_api_path(script_fname, contents_manager.root_dir) log = contents_manager.log script_fullpath = os.path.join(dir_path, ".nbexports", script_repopath) os.makedirs(os.path.dirname(script_fullpath), exist_ok=True) log.info("Saving script /%s", script_fullpath) with io.open(script_fullpath, 'w', encoding='utf-8', newline='\n') as f: f.write(script)
def perm_to_403(self, os_path=''): """context manager for turning permission errors into 403.""" try: yield except (OSError, IOError) as e: if e.errno in {errno.EPERM, errno.EACCES}: # make 403 error message without root prefix # this may not work perfectly on unicode paths on Python 2, # but nobody should be doing that anyway. if not os_path: os_path = str_to_unicode(e.filename or 'unknown file') path = to_api_path(os_path, root=self.root_dir) raise HTTPError(403, u'Permission denied: %s' % path) else: raise
def script_post_save(model, os_path, contents_manager, **kwargs): """Save a copy of notebook to the corresponding language source script. For example, when you save a `foo.ipynb` file, a corresponding `foo.py` python script will also be saved in the same directory. However, existing config files I found online (including the one written in the official documentation), will also create an `Untitile.txt` file when you create a new notebook, even if you have not pressed the "save" button. This is annoying because we usually will rename the notebook with a more meaningful name later, and now we have to rename the generated script file, too! Therefore we make a change here to filter out the newly created notebooks by checking their names. For a notebook which has not been given a name, i.e., its name is `Untitled.*`, the corresponding source script will not be saved. Note that the behavior also applies even if you manually save an "Untitled" notebook. The rationale is that we usually do not want to save scripts with the useless "Untitled" names. """ # only process for notebooks if model["type"] != "notebook": return script_exporter = ScriptExporter(parent=contents_manager) base, __ = os.path.splitext(os_path) # do nothing if the notebook name ends with `Untitled[0-9]*` regex = re.compile(r"Untitled[0-9]*$") if regex.search(base): return script, resources = script_exporter.from_filename(os_path) script_fname = base + resources.get("output_extension", ".txt") log = contents_manager.log log.info("Saving script at /%s", to_api_path(script_fname, contents_manager.root_dir)) script = fix_cli(script) with io.open(script_fname, "w", encoding="utf-8") as f: f.write(script)
def _post_save_script(model, os_path, contents_manager, **kwargs): """convert notebooks to Python script after save with nbconvert replaces `jupyter notebook --script` """ from nbconvert.exporters.script import ScriptExporter warnings.warn("`_post_save_script` is deprecated and will be removed in Notebook 5.0", DeprecationWarning) if model['type'] != 'notebook': return global _script_exporter if _script_exporter is None: _script_exporter = ScriptExporter(parent=contents_manager) log = contents_manager.log base, ext = os.path.splitext(os_path) script, resources = _script_exporter.from_filename(os_path) script_fname = base + resources.get('output_extension', '.txt') log.info("Saving script /%s", to_api_path(script_fname, contents_manager.root_dir)) with io.open(script_fname, 'w', encoding='utf-8') as f: f.write(script)
def script_post_save(model, os_path, contents_manager, **kwargs): """convert notebooks to Python script after save with nbconvert replaces `jupyter notebook --script` """ from nbconvert.exporters.script import ScriptExporter if model["type"] != "notebook": return global _script_exporter if _script_exporter is None: _script_exporter = ScriptExporter(parent=contents_manager) log = contents_manager.log base, ext = os.path.splitext(os_path) script, resources = _script_exporter.from_filename(os_path) script_fname = base + resources.get("output_extension", ".txt") log.info("Saving script /%s", to_api_path(script_fname, contents_manager.root_dir)) with io.open(script_fname, "w", encoding="utf-8") as f: f.write(script)
def save_as_html(os_path, contents_manager): from nbconvert.exporters.html import HTMLExporter global _html_exporter if _html_exporter is None: _html_exporter = HTMLExporter(parent=contents_manager) log = contents_manager.log base, ext = os.path.splitext(os_path) html_fname = base + '.html' html, resources = _html_exporter.from_filename(os_path) if resources.get('output_extension') == '.txt': # prevent annoying behaviour of also saving as file.txt return html_fname = base + resources.get('output_extension', '.txt') log.info("Saving HTML /%s", to_api_path(html_fname, contents_manager.root_dir)) with io.open(html_fname, 'w', encoding='utf-8') as f: f.write(html)
def save_as_python(os_path, contents_manager): from nbconvert.exporters.script import ScriptExporter global _script_exporter if _script_exporter is None: _script_exporter = ScriptExporter(parent=contents_manager) log = contents_manager.log base, ext = os.path.splitext(os_path) py_fname = base + '.py' script, resources = _script_exporter.from_filename(os_path) if resources.get('output_extension') == '.txt': # prevent annoying behaviour of also saving as file.txt return script_fname = base + resources.get('output_extension', '.txt') log.info("Saving script /%s", to_api_path(script_fname, contents_manager.root_dir)) with io.open(script_fname, 'w', encoding='utf-8') as f: f.write(script)