python - Jupyter Notebook在启动Python内核时自动导入模块

标签 python jupyter-notebook

我正在一个 Jupyter 目录中工作,其中包含不同语言的不同笔记本。当我打开 Python 笔记本时,我希望 Python 内核自动导入特定模块(如果在同一文件夹中找到)。

例如,假设我有下面的文件树:

root_folder
  |- subfolder_1
  |    |- script1.ipynb
  |    |- script2.ipynb
  |    `- startup.py
  `- subfolder_2
       `- script3.ipynb

我希望 Python 内核在 script1.ipynbscript2.ipynb 打开时自动导入 startup.py 模块。对于 script3.ipynb,我不想引发任何错误(但尝试导入 startup.py 如果它存在)。

目标是提供一些特定于文件夹的功能而无需手动导入此模块

我知道编写 fromstartup import * 并不“昂贵”,但我不想这样做。

最佳答案

您可以利用启动文件。

您应该能够在 <profile>/startup 中找到它们目录。

复制自 docs :

If you want some code to be run at the beginning of every IPython session with a particular profile, the easiest way is to add Python (.py) or IPython (.ipy) scripts to your /startup directory. Files in this directory will always be executed as soon as the IPython shell is constructed, and before any other code or scripts you have specified. If you have multiple files in the startup directory, they will be run in lexicographical order, so you can control the ordering by adding a ‘00-‘ prefix.

关于python - Jupyter Notebook在启动Python内核时自动导入模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58771018/

相关文章:

python - Django 1.4 SimpleListfilter 排序错误

python - 删除 RISE 中的问号和进入/退出按钮(Jupyter Notebook)

python - 在 Jupyter Notebook 中居中 HTML 表格和文本

python - Google Collab Notebook与普通的Python脚本创建了不同类型的绘图大小

android - 仅使用 kv 文件在 kivy 中创建 DropDown

python - 如何避免在网络爬行时出现断词

python - difflib.HTMLDiff.make_file() 的输出未在浏览器中呈现

Python matplotlib 图例如何减少帧左边缘和标记之间的距离

jupyter - nbconvert 从命令行输出结果执行 Jupyter notebook

python - 有没有办法在 Visual Studio Code 中删除 Jupyter "Run Cell"按钮?