如何在每个jupyter笔记本内核之前运行Python代码 [英] How to run Python code before every jupyter notebook kernel

查看:197
本文介绍了如何在每个jupyter笔记本内核之前运行Python代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个代码片段,每次打开jupyter笔记本时都想运行(在我的情况下,它正在打开Spark连接).假设我将代码保存在.py脚本中:

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-

-- startup.py --

sc = "This is a spark connection"

我希望每次打开内核时都能运行该代码段.我发现了一些有关 Jupyter配置文件的东西.当我尝试运行

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?

推荐答案

我建议按照您的建议创建一个启动文件,并通过

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.

专业版:不会使笔记本混乱

缺点:进行细微更改更困难.

Con: More difficult to make small changes.

这篇关于如何在每个jupyter笔记本内核之前运行Python代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆