动态重新加载Cython模块

Reloading Cython modules on the fly(动态重新加载Cython模块)
本文介绍了动态重新加载Cython模块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试自动更新我的python程序动态使用的Cython.so模块。在我下载新模块和del moduleimport module之后,Python似乎仍在导入旧版本。

在this question中,我尝试了此操作,但不起作用:

from importlib import reload
import pyximport
pyximport.install(reload_support=True)
import module as m
reload(m)

在this question中,我也尝试过这个,但也不起作用:

del sys.modules['module']
del module
import module

我也试过了,但没有成功:

from importlib import reload
import my_module

my_module = reload(my_module)

您知道如何动态导入Cython.so文件吗?


编辑:添加更新检查和下载代码

update_filename = "my_module.cpython-37m-darwin.so"

if __name__ == '__main__':
    response = check_for_update()
    if response != "No new version available!":
        print (download_update(response))

def check_for_update():
    print("MD5 hash: {}".format(md5(__file__)))
    s = setup_session()
    data = {
        "hash": md5(__file__),
        "type": "md5",
        "platform": platform.system()
    }
    response = s.post(UPDATE_CHECK_URL, json=data)
    return response.text

def download_update(url):
    s = setup_session()
    with s.get(url, stream=True) as r:
        r.raise_for_status()
        with open(update_filename, 'wb') as f:
            for chunk in r.iter_content(chunk_size=8192): 
                if chunk:
                    f.write(chunk)
    return update_filename

下载了新的so文件后,我手动键入了上面列出的命令。

推荐答案

所以我一直没有找到正确的方法,但通过将我的程序拆分成两个独立的部分来解决问题:

  1. 一个不变的‘runner’部分,它只是导入.so文件(或Windows上的.PYD文件)并在其中运行函数
  2. 包含核心逻辑的实际.so(或.PYD)文件

不变的脚本检查.so/.PYD文件的更新(使用其SHA256散列+模块版本),当找到更新版本时,它会下载该文件并替换现有的.so/.PYD文件并重新启动,从而加载更新的模块。

当没有找到更新时,它会导入本地.so/.PYD文件并在其中运行一个函数。这种方法在Windows和OSX上都适用。

运行者脚本(run.py)

import requests, os, sys
from pathlib import Path
from shutil import move

original_filename = "my_module.cp38-win32.pyd" # the filename of the Cython module to load
update_filename = f"{original_filename}.update"
UPDATE_SERVER = "https://example.com/PROD/update-check"

def check_for_update():
    replace_current_pyd_with_previously_downloaded_update() # Actually perform the update
    # Add your own update check logic here
    # This one checks with {UPDATE_SERVER} for updates to {original_filename} and returns the direct link to the updated PYD file if an update exists
    s = requests.Session()
    data = {
        "hash": sha256(original_filename),
        "type": "sha256",
        "current_version": get_daemon_version(),
        "platform": platform.system()
    }
    response = s.post(UPDATE_SERVER, json=data)
    return response.text # direct link to newer version of PYD file if update exists

def download_update(url):
    # Download updated PYD file from update server and write/replace {update_filename}

def replace_current_pyd_with_previously_downloaded_update():
    print("Checking for previously downloaded update file")
    update_file_path = Path(update_filename)
    if update_file_path.is_file():
        print(f"Update file found! Performing update by replacing {original_filename} with the updated version and deleting {update_filename}")
        move(update_filename, original_filename)
    else:
        print("No previously downloaded update file found. Checking with update server for new versions")

def get_daemon_version():
    from my_module import get_version
    return get_version() # my_module.__version__.lower().strip()

def restart():
    print ("Restarting to apply update...
")
    python = sys.executable
    os.execl(python, python, *sys.argv)

def apply_update():
    restart()

def start_daemon():
    import my_module
    my_module.initiate()
    my_module.start()

if __name__ == "__main__":
    response = None
    print ("Checking to see if an update is available...")
    try:
        response = check_for_update()
    except Exception as ex:
        print ("Unable to check for updates")
        pass
    if response is None:
        print ("Unable to check for software updates. Using locally available version.")
        start_daemon()
    elif response != "No new version available!" and response != '':
        print ("Newer version available. Updating...")
        print ("Update downloaded: {}".format(download_update(response)))
        apply_update()
        start_daemon()
    else:
        print ("Response from update check API: {}
".format(response))
        start_daemon()

.so/.PYD文件

实际的.so文件(在本例中为.PYD文件)应包含名为get_version的方法,该方法应返回模块的版本,并且您的更新服务器应包含用于确定是否有更新可用于(SHA256+MODULE_VERSION)组合的逻辑。

您当然可以以完全不同的方式实现更新检查。

这篇关于动态重新加载Cython模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Leetcode 234: Palindrome LinkedList(Leetcode 234:回文链接列表)
How do I read an Excel file directly from Dropbox#39;s API using pandas.read_excel()?(如何使用PANDAS.READ_EXCEL()直接从Dropbox的API读取Excel文件?)
subprocess.Popen tries to write to nonexistent pipe(子进程。打开尝试写入不存在的管道)
I want to realize Popen-code from Windows to Linux:(我想实现从Windows到Linux的POpen-code:)
Reading stdout from a subprocess in real time(实时读取子进程中的标准输出)
How to call type safely on a random file in Python?(如何在Python中安全地调用随机文件上的类型?)