KnowledgeHub
Questions
Tags
Users
Search
Alex Rivera
|
Logout
Edit Question
Title
Body
The following code allows you to modify the contents of runtime.py at run time. In other words, you don't have to interrupt 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() The module imported at runtime is: # runtime.py def function(): print("I am version one of runtime.py") This primitive mechanism allows you to "how-swap" Python code (a la Erlang). Is there a better alternative? Please notice that this is a merely academic question, as I don't have the necessity to do anything like this. However, I am interested in learning more about the Python runtime. Edit : I created the following solution: an Engine object provides an interface to the functions contained in a module (in this case the module is called engine.py ). The Engine object also spawns a thread which monitors for changes in the source file and, if changes are detected, it calls the notify() method on the engine, which reloads the source file. In my implementation, the change detection is based on polling every frequency seconds checking the SHA1 checksum of the file, but other implementations are possible. In this example every change detected is logged to a file called hotswap.log , where the checksum is registered. Other mechanisms for detecting changes could be a server or the use of inotify in the Monitor thread. 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.en
Tags (comma-separated)
Save Edits
Cancel