繁体   English   中英

在特定路径中自动加载python文件

[英]Autoreload of python file in specific path

工作情况

我有一个带有基本功能的hello.py文件

def say_hello()
    print("hello world")
    return

notebook.ipynb 在同一目录中 (使“导入”工作)

%load_ext autoreload
%autoreload 2
import hello

然后每次我更新hello.py文件时,autoreload工作:

hello.say_hello() 

Out >>>  "Hello world with autoreload working"



有问题的情况

hello.py文件不在同一目录中时,我不能使用“import”,所以我有:

%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文件?

这是一个ImportError python版本 - 3.7。

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

暂无
暂无

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

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