How to run Python code before every jupyter notebook kernel

旧巷老猫 提交于 2019-12-30 18:55:00

问题


Suppose I have a code snippet that I'd like to run every time I open a jupyter notebook (in my case it's opening up a Spark connection). Let's say I save that code in a .py script:

-- startup.py --

sc = "This is a spark connection"

I want to be able to have that code snippet run every time I open a kernel. I've found some stuff about the Jupyter Configuration File, but it doesn't seem like variables defined there show up when I try to run

print(sc)

in a notebook. Is there a command-line option that I could use -- something like:

jupyter notebook --startup-script startup.py

or do I have to include something like

from startup import sc, sqlContext

in all of the notebooks where I want those variables to be defined?


回答1:


I'd recommend to create a startup file as you suggested, and include it via

%load ~/.jupyter/startup.py

This will paste the content of the file into the cell, which you can then execute.

Alternatively, you can write a minimal, installable package that contains all your startup code.

Pro: Doesn't clutter your notebook

Con: More difficult to make small changes.



来源:https://stackoverflow.com/questions/49677847/how-to-run-python-code-before-every-jupyter-notebook-kernel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!