我正在一个 Jupyter 目录中工作,其中包含不同语言的不同笔记本。当我打开 Python 笔记本时,我希望 Python 内核自动导入特定模块(如果在同一文件夹中找到)。
例如,假设我有下面的文件树:
root_folder
|- subfolder_1
| |- script1.ipynb
| |- script2.ipynb
| `- startup.py
`- subfolder_2
`- script3.ipynb
我希望 Python 内核在 script1.ipynb
或 script2.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/