[Python] Jupyter notebook configuration: how to always run a cell with any notebook recreated?

Discussão em 'Python' iniciado por Stack, Janeiro 26, 2025.

  1. Stack

    Stack Membro Participativo

    I have this jupyter notebook cell which I always run at the start of every notebook that I run, the cell is

    import warnings
    warnings.filterwarnings('ignore')
    from IPython.core.interactiveshell import InteractiveShell
    InteractiveShell.ast_node_interactivity = "all"
    from IPython.core.display import display, HTML
    display(HTML("<style>.container { width:90% !important; }</style>"))


    I have never looked at the jupyter notebook configuration files so I do not know if its possible to have this kind of set up. But the goal is to have this cell run at the start-up of every notebook. Preferably without needing the see the cell in the newly started notebook.

    Note: I always install jupyter notebook on a per virtual environment basis (I use pipenv to manage my environments). I have a custom script which installs all the requirements for jupyter notebook and other CLI tools like Ipython in each virtual environment i create. So I dont know if there are global jupyter-notebook settings which I could configure with the above described behavior or because of my set up I have to re-configure this setup for every environment I create, in which I make use of notebooks.

    Does anyone know if this is possible to set up?

    In case it helps with answer this question, this installation file looks like:

    #!/usr/bin/env python

    import subprocess
    import os
    print(f"Current working dirctory: { os.getcwd() }")
    pipenv_name = os.environ['VIRTUAL_ENV'].split("/")[-1]
    print(f"Installing ipykernel to environment: {pipenv_name}")
    python_loc = subprocess.check_output(["which", "python"]).decode("utf-8").rstrip("\n")
    pip_loc = subprocess.check_output(["which", "pip"]).decode("utf-8").rstrip("\n")

    print("python location: ", python_loc)
    print("pip location: ", pip_loc)
    print("Install ipykernel to user in environment")

    try:
    subprocess.check_call([pip_loc,"install","ipykernel", "jupyterlab", "jupyter_nbextensions_configurator", "jupyter-http-over-ws", "ipywidgets", "widgetsnbextension"])
    except subprocess.CalledProcessError:
    subprocess.check_call(["pip","install", "ipykernel", "jupyterlab", "jupyter_nbextensions_configurator", "jupyter-http-over-ws", "ipywidgets", "widgetsnbextension"])
    pass
    try:
    subprocess.check_call([str(python_loc), "-m", "ipykernel", "install", "--user", f"--name={pipenv_name}"])
    except subprocess.CalledProcessError:
    subprocess.check_call(["python3","-m","ipykernel","install","--user",f"--name={pipenv_name}"])
    pass

    Continue reading...

Compartilhe esta Página