【问题标题】:How can I reload a python class if file is changed on disk?如果磁盘上的文件发生更改,如何重新加载 python 类?
【发布时间】:2021-09-26 08:30:00
【问题描述】:

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

【问题讨论】:

    标签: python class reload if-modified-since


    【解决方案1】:

    这个方法似乎有效:

    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 时, 类被重新加载并且新对象 返回反映了新的类字段。

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        猜你喜欢
        • 2020-12-01
        • 1970-01-01
        • 2013-05-13
        • 2010-12-01
        • 2019-04-20
        • 2019-11-20
        • 2011-03-11
        • 2012-10-12
        • 2019-01-27
        相关资源
        最近更新 更多