0

为了支持存储在源类文件中并用作具有字段的对象的参数的运行时更改,我如何检查对象的源文件自运行时开始或自上次重新加载以来是否被修改,并重新加载类并制作对象的新实例?

4

2 回答 2

0

您可能需要考虑使用像watchdog这样的库,它可以让您在文件更改时触发处理程序。您可以将参数存储在数据文件中,而不是将参数与代码并置,使用在启动时调用的数据加载器方法以及每当基础数据文件发生更改时调用的数据加载器方法。

于 2021-07-18T09:16:50.603 回答
0

这种方法似乎有效:

def reload_class_if_modified(obj:object, every:int=1)->object:
    """
    Reloads an object if the source file was modified since runtime started or since last reloaded

    :param obj: the original object
    :param every: only check every this many times we are invoked

    :returns: the original object if classpath file has not been modified 
              since startup or last reload time, otherwise the reloaded object
    """
    reload_class_if_modified.counter+=1
    if reload_class_if_modified.counter>1 and reload_class_if_modified.counter%every!=0:
        return obj
    try:
        module=inspect.getmodule(obj)
        cp=Path(module.__file__)
        mtime=cp.stat().st_mtime
        classname=type(obj).__name__

        if (mtime>reload_class_if_modified.start_time and (not (classname in reload_class_if_modified.dict))) \
                or ((classname in reload_class_if_modified.dict) and mtime>reload_class_if_modified.dict[classname]):
            importlib.reload(module)
            class_ =getattr(module,classname)
            o=class_()
            reload_class_if_modified.dict[classname]=mtime
            return o
        else:
            return obj
    except Exception as e:
        logger.error(f'could not reload {obj}: got exception {e}')
        return obj

reload_class_if_modified.dict=dict()
reload_class_if_modified.start_time=time()
reload_class_if_modified.counter=0

像这样使用它:

import neural_mpc_settings
from time import sleep as sleep
g=neural_mpc_settings()
while True:
    g=reload_class_if_modified(g, every=10)
    print(g.MIN_SPEED_MPS, end='\r')
    sleep(.1)

其中 neural_mpc_settings 是

class neural_mpc_settings():
    MIN_SPEED_MPS = 5.0

当我更改磁盘上的neural_mpc_settings.py时,将重新加载该类,并且返回的新对象反映了新的类字段。

于 2021-07-18T09:01:26.387 回答