Hot-swapping of Python running program

不问归期 提交于 2019-12-02 19:22:00
Phil

You could poll the runtime.py file, waiting for it to change. Once it changes, just call

reload(runtime)

Any time I'm debugging a python module, I use this approach in the interactive python command prompt (except I manually call reload(), I don't poll anything).

EDIT: To detect changes in a file, check out this SO question. Polling may be the most reliable option, but I would only reload the file if the modified time is updated, rather than reloading it on every poll. You should also consider catching exceptions when you reload, especially syntax errors. And you may or may not encounter problems with thread safety.

globe = __import__('copy').copy(globals())
while True:
    with open('runtime.py', 'r') as mod:
        exec mod in globe
    __import__('time').sleep(1)

Will repeatedly read and run runtime.py with a nearly unpolluted globals() and no locals(), and won't pollute the global scope, but all of runtime's namespace will be available in globe

If you want hot-swap code that found as when you use import out of functions etc, you need overwrite a global var of module, if for example you use:

import mylib

You need when load module in code asign to mylib the new module. Other cuestion is try this in program that use threads for know if is secure with threads and, when use multiprocessing this only found in one process, for change code in all process all need load new code, is necesary try if is secure in multiproces.

And, is interessting check first if have new code or not for not load same code. And think in Python only you can load a new module and replace variable name of module, but if you really need a good hot change code see Erlang language and OTP, it's very good.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!