Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

JN 7 execute, get notebook name, save from within a notebook #7293

Open
liquidcarbon opened this issue Mar 11, 2024 · 5 comments
Open

JN 7 execute, get notebook name, save from within a notebook #7293

liquidcarbon opened this issue Mar 11, 2024 · 5 comments

Comments

@liquidcarbon
Copy link

Problem

Hello, I used to run the following in notebook 6.5:

class NotebookRunner:
    """Helper class for rendering the notebook to HTML using Quarto.
    
    This only works in the context of a Jupyter notebook.
    
    Usage
    -----
    # place in a cell, launch with Shift+Enter
    # all cells below will be executed automatically
    # if no errors, the notebooks will be saved and publish will happen
    nr = NotebookPublisher()  # retrieves notebook name from browser and passes the value python variable
   
    """
    
    JS = """
    Jupyter.notebook.kernel.execute(
        "NB_NAME = " + "\'" + window.document.getElementById("notebook_name").innerHTML + "\'"
    );
    function runCellsBelow() {
        var cells = Jupyter.notebook.get_cells();
        for (var i = Jupyter.notebook.get_selected_index(); i < cells.length; i++) {
            if (cells[i].cell_type === 'code') {
                Jupyter.notebook.execute_cell_range(i, i + 1);
            }
        }
    }
    runCellsBelow();
    """
    
    def __init__(self, run=True, **kwargs):
        """Checks that Quarto is available and saves the current notebook."""

        log.info(" ⬇ your notebook is running ⬇ ")
        if run: self.run(**kwargs)
        return
    
    def run(self, **kwargs):
        """Runs the current notebook."""
        
        from IPython.display import display, Javascript
        display(Javascript(self.JS))
        return

The running part worked well, the saving part never properly worked.
But now I understand the Jupyter javascript global is gone, so I'm getting Javascript Error: Jupyter is not defined

How do I run and save from within a notebook? Ideally, my last cell is "publish" (via nbconvert or quarto) and the notebook is saved right before then. What's the proper way to do this now?

Additional context

#7225
#6949
#6394

@liquidcarbon liquidcarbon added enhancement status:Needs Triage Applied to issues that need triage labels Mar 11, 2024
@RRosio
Copy link
Collaborator

RRosio commented Mar 12, 2024

Thank you for opening this issue @liquidcarbon, as mentioned in the issues you have linked to. Have you tried the suggestions in #6949 (comment)?

@liquidcarbon
Copy link
Author

Hi, thanks for your response!
It's not completely clear how to proceed based on this comment. Hope I don't have to develop a whole extension for this!

Or is it as simple as replacing Jupyter.notebook with window.jupyterapp?

@RRosio
Copy link
Collaborator

RRosio commented Mar 12, 2024

No problem @liquidcarbon! You will likely need to add more than just the window.jupyterapp for most of the functionality. For something like saving a notebook it is window.jupyterapp.commands.execute('docmanager:save') that does the trick. All commands can be found in this page of the documentation! For some of the functions referenced in the code snippet I couldn't find direct replacements but I could have missed something.

@liquidcarbon
Copy link
Author

liquidcarbon commented Mar 13, 2024

Thanks @RRosio !

This works when you start jupyter-lab with --expose-app-in-browser flag

Javascript("""
let app = window.jupyterapp;
// app.commands.execute('notebook:run-all-cells')
// app.commands.execute('notebook:run-cell-and-select-next')
app.commands.execute('docmanager:save')
""")

But I'm still unclear how to get the name of the running notebook.
This logs the page title to the console.

%%javascript
let notebook_name = window.document.querySelector('title').textContent;
console.log(notebook_name);

But you can't seem to be able to move variables easily between python and JS like you could in old JN.

Here's one option via ipylab: jupyterlab/jupyterlab#13020 (comment)

Appreciate any pointers!

@JasonWeill JasonWeill removed status:Needs Info status:Needs Triage Applied to issues that need triage labels Mar 19, 2024
@liquidcarbon
Copy link
Author

Answered in jtpio/ipylab#139

import os
os.environ.get('JPY_SESSION_NAME')

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants