【问题标题】:Autoreload of python file in specific path在特定路径中自动重新加载 python 文件
【发布时间】: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


    【解决方案1】:

    这是一个ImportError python 版本 - 3.7。

    如果找不到模块的规范,则让importlib.reload() 引发 ImportError。

    【讨论】:

    • 我更新了我的问题。不幸的是,我不认为这是路径的问题,因为它是第一次正确导入(say_hello() 正在工作),但在修改 python 文件时不是
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-20
    • 1970-01-01
    • 2013-07-21
    相关资源
    最近更新 更多