jupyter运行python代码_如何在每个jupyter笔记本内核之前运行Python代码

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?

解决方案

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值