Configure a first cell by default in Jupyter notebooks

后端 未结 6 581
再見小時候
再見小時候 2021-02-02 01:03

TIs there a way to configure a default first cell for a specific python kernel in the Jupyter notebook? I agree that default python imports go against good coding practices.

6条回答
  •  旧时难觅i
    2021-02-02 02:02

    I came up with this:

    1 - Create a startup script that will check for a .jupyternotebookrc file:

    # ~/.ipython/profile_default/startup/run_jupyternotebookrc.py
    
    import os
    import sys
    
    if 'ipykernel' in sys.modules: # hackish way to check whether it's running a notebook
        path = os.getcwd()
        while path != "/" and ".jupyternotebookrc" not in os.listdir(path):
            path = os.path.abspath(path + "/../")
        full_path = os.path.join(path, ".jupyternotebookrc")
        if os.path.exists(full_path):
            get_ipython().run_cell(open(full_path).read(), store_history=False)
    

    2 - Create a configuration file in your project with the code you'd like to run:

    # .jupyternotebookrc in any folder or parent folder of the notebook
    
    %load_ext autoreload
    %autoreload 2
    %matplotlib inline
    
    import numpy as np
    

    You could commit and share your .jupyternotebookrc with others, but they'll also need the startup script that checks for it.

提交回复
热议问题