简体   繁体   English

如何在Jupyter笔记本中自动重载由load magic加载的代码?

[英]How to auto-reload code loaded by load magic in Jupyter notebook?

Jupyter Notebook has a %load magic that can load code into a cell of a notebook. Jupyter Notebook具有%load magic,可以将代码加载到笔记本的单元格中。

%load start.py

This line loads the content of start.py into the current cell. 此行将start.py的内容start.py到当前单元格中。 The magic is automatically commented out after execution. 执行后,魔法会自动注释掉。

# %load start.py
import numpy as np
import pandas as pd

Jupyter Notebook also has a %autoreload extension that can reload modules before executing code. Jupyter Notebook还有一个%autoreload扩展,可以在执行代码之前重新加载模块。

%load_ext autoreload
%autoreload 2
from utils import load_data

If there is a change in the load_data function, this extension can detect and auto-reload the new function before execution. 如果load_data函数发生更改,则此扩展可以在执行之前检测并自动重新加载新函数。

Is there a way to combine the functionality of these two? 有没有办法结合这两个功能? In other words, if the content of start.py change, how can I automatically detect the change and reload it into the cell before running code? 换句话说,如果start.py的内容start.py变化,如何在运行代码之前自动检测更改并将其重新加载到单元格中?

For example, if the content of start.py is now 例如,如果start.py的内容现在是

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

I would like the cell to be reloaded to become: 我希望重新加载单元格成为:

# %load start.py
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

I think you're trying to mix things beyond the point they were intended. 我认为你试图将事情超出他们想要的范围。

If you want a hack, as you mention you could import a function from within start.py , then %autoreload will give you the functionality you want. 如果你想要hack,正如你所提到的,你可以从start.py导入一个函数,那么%autoreload将为你提供你想要的功能。 You could then mix with this if you wanted to see the contents of the .py file: 如果你想看到.py文件的内容,你可以混合使用它:

with open("start.py") as f:
    print(f.read())

You could then easily copy and paste into a cell if needed. 如果需要,您可以轻松地复制并粘贴到单元格中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM