【发布时间】:2019-10-30 20:27:49
【问题描述】:
工作情况
我有一个带有基本功能的hello.py文件
def say_hello()
print("hello world")
return
还有一个notebook.ipynb 在同一目录中(使“导入”工作)
%load_ext autoreload
%autoreload 2
import hello
然后每次我更新 hello.py 文件时,自动重载都会起作用:
hello.say_hello()
Out >>> "Hello world with autoreload working"
有问题的情况
当hello.py 文件不在同一个目录中时,我不能使用“导入”,所以我有:
%load_ext autoreload
%autoreload 2
from importlib.machinery import SourceFileLoader
hello = SourceFileLoader("hello", '/path/to/hello.py').load_module()
起初它有效:
hello.say_hello()
Out >>> "Hello world"
但是在我编辑了python文件之后:
def say_hello()
print("hello world again")
return
并重新执行该函数,它返回文件的先前版本并抛出错误
hello.say_hello()
Out >>> "Hello world"
[autoreload of failed: Traceback (most recent call last):
File "C:\Program Files\Python36\Lib\site-
packages\IPython\extensions\autoreload.py", line 244, in check
superreload(m, reload, self.old_objects)
File "C:\Program Files\Python36\Lib\site-packages\IPython\extensions\autoreload.py", line 376, in superreload
module = reload(module)
File "C:\Program Files\Python36\Lib\imp.py", line 314, in reload
return importlib.reload(module)
File "C:\Program Files\Python36\Lib\importlib\__init__.py", line 166, in reload
_bootstrap._exec(spec, module)
File "<frozen importlib._bootstrap>", line 589, in _exec
AttributeError: 'NoneType' object has no attribute 'name'
]
如何从 Jupyter 笔记本自动重新加载特定路径中的 Python 文件?
【问题讨论】:
标签: python module jupyter-notebook ipython reload