下面的代码允许您在运行时修改runtime.py
的内容。换句话说,您不必中断runner.py
。
#runner.py
import time
import imp
def main():
while True:
mod = imp.load_source("runtime", "./runtime.py")
mod.function()
time.sleep(1)
if __name__ == "__main__":
main()
运行时导入的模块是:
# runtime.py
def function():
print("I am version one of runtime.py")
这个基本机制允许您“如何交换”Python代码(la Erlang)。有更好的选择吗?
请注意,这只是一个学术问题,因为我没有必要这样做。不过,我有兴趣进一步了解Python运行时。
编辑:
我创建了以下解决方案:一个Engine
对象为模块中包含的函数提供一个接口(在本例中,该模块称为engine.py
)。Engine
对象还生成一个线程,该线程监视源文件中的更改,如果检测到更改,则调用引擎上的notify()
方法,该方法重新加载源文件。
在我的实现中,更改检测基于每frequency
秒轮询一次检查文件的SHA1校验和,但是其他实现是可能的。
在本例中,检测到的每个更改都会记录到名为hotswap.log
的文件中,在该文件中会注册校验和。
检测更改的其他机制可以是服务器或在Monitor
线程中使用inotify
。
import imp
import time
import hashlib
import threading
import logging
logger = logging.getLogger("")
class MonitorThread(threading.Thread):
def __init__(self, engine, frequency=1):
super(MonitorThread, self).__init__()
self.engine = engine
self.frequency = frequency
# daemonize the thread so that it ends with the master program
self.daemon = True
def run(self):
while True:
with open(self.engine.source, "rb") as fp:
fingerprint = hashlib.sha1(fp.read()).hexdigest()
if not fingerprint == self.engine.fingerprint:
self.engine.notify(fingerprint)
time.sleep(self.frequency)
class Engine(object):
def __init__(self, source):
# store the path to the engine source
self.source = source
# load the module for the first time and create a fingerprint
# for the file
self.mod = imp.load_source("source", self.source)
with open(self.source, "rb") as fp:
self.fingerprint = hashlib.sha1(fp.read()).hexdigest()
# turn on monitoring thread
monitor = MonitorThread(self)
monitor.start()
def notify(self, fingerprint):
logger.info("received notification of fingerprint change ({0})".\
format(fingerprint))
self.fingerprint = fingerprint
self.mod = imp.load_source("source", self.source)
def __getattr__(self, attr):
return getattr(self.mod, attr)
def main():
logging.basicConfig(level=logging.INFO,
filename="hotswap.log")
engine = Engine("engine.py")
# this silly loop is a sample of how the program can be running in
# one thread and the monitoring is performed in another.
while True:
engine.f1()
engine.f2()
time.sleep(1)
if __name__ == "__main__":
main()
engine.py
文件:
# this is "engine.py"
def f1():
print("call to f1")
def f2():
print("call to f2")
日志样本:
INFO:root:received notification of fingerprint change (be1c56097992e2a414e94c98cd6a88d162c96956)
INFO:root:received notification of fingerprint change (dcb434869aa94897529d365803bf2b48be665897)
INFO:root:received notification of fingerprint change (36a0a4b20ee9ca6901842a30aab5eb52796649bd)
INFO:root:received notification of fingerprint change (2e96b05bbb8dbe8716c4dd37b74e9f58c6a925f2)
INFO:root:received notification of fingerprint change (baac96c2d37f169536c8c20fe5935c197425ed40)
INFO:root:received notification of fingerprint change (be1c56097992e2a414e94c98cd6a88d162c96956)
INFO:root:received notification of fingerprint change (dcb434869aa94897529d365803bf2b48be665897)
再次-这是一个学术讨论,因为我现在不需要热交换Python代码。不过,我喜欢能够稍微了解运行时,并认识到什么是可能的,什么是不可能的。注意,如果加载机制正在使用资源,则可以添加锁;如果模块未成功加载,则可以添加异常处理。
评论?
您可以轮询runtime.py文件,等待其更改。一旦改变了,打电话
在调试python模块时,我在交互式python命令提示符中使用这种方法(除了手动调用reload(),我不轮询任何内容)。
编辑: 要检测文件中的更改,请签出this SO question。轮询可能是最可靠的选项,但我只在修改的时间更新时重新加载文件,而不是在每次轮询时重新加载它。您还应该考虑在重新加载时捕获异常,特别是语法错误。您可能会遇到也可能不会遇到线程安全问题。
如果希望在使用“从函数导入”等时找到热交换代码,则需要覆盖模块的全局变量,例如,如果使用:
在代码asign中加载模块时,需要将新模块分配给mylib。另一个提示是,在使用线程的程序中尝试此操作,以了解线程是否安全,并且,当使用多处理时,仅在一个进程中发现此操作,对于所有进程中的更改代码都需要加载新代码,则必须在多进程中尝试此操作是否安全。
并且,如果有新的代码或者不加载相同的代码,首先要检查是否有趣。在Python中,只有您可以加载一个新模块并替换模块的变量名,但是如果您真的需要一个好的热更改代码,请参阅Erlang语言和OTP,这非常好。
将以几乎没有污染的
globals()
和locals()
重复读取和运行runtime.py
,并且不会污染全局作用域,但是所有运行时的命名空间都将在globe
中可用相关问题 更多 >
编程相关推荐