简体   繁体   English

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

[英]Autoreload of python file in specific path

Working situation 工作情况

I have a hello.py file with the basic function 我有一个带有基本功能的hello.py文件

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

And a notebook.ipynb in the same directory (making the "import" work) notebook.ipynb 在同一目录中 (使“导入”工作)

%load_ext autoreload
%autoreload 2
import hello

Then everytime I update the hello.py file, the autoreload works : 然后每次我更新hello.py文件时,autoreload工作:

hello.say_hello() 

Out >>>  "Hello world with autoreload working"



Problematic situation 有问题的情况

When the hello.py file is not in the same directory I can not use "import" so I have: hello.py文件不在同一目录中时,我不能使用“import”,所以我有:

%load_ext autoreload
%autoreload 2

from importlib.machinery import SourceFileLoader
hello = SourceFileLoader("hello", '/path/to/hello.py').load_module()

At first it works : 起初它起作用:

hello.say_hello()

Out >>> "Hello world"

But after I edit the python file : 但是在我编辑python文件之后:

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

And re-execute the function, it returns the previous version of the file AND throws an error 并重新执行该函数,它返回文件的先前版本并抛出错误

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'
]

How to autoreload a Python file in a specific path, from a Jupyter notebook ? 如何从Jupyter笔记本中自动加载特定路径中的Python文件?

This is an ImportError python version - 3.7. 这是一个ImportError python版本 - 3.7。

Have importlib.reload() raise ImportError if the module's spec is not found. 如果找不到模块的规范,请使用importlib.reload()引发ImportError。

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

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