Created
July 14, 2017 14:27
-
-
Save tag1216/66d3c167c9f7e319a5af5e1639639663 to your computer and use it in GitHub Desktop.
ディレクトリ内のPythonモジュールを動的インポート/リロード
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
import sys | |
import time | |
from glob import glob | |
from importlib import import_module, reload | |
from watchdog.events import FileSystemEventHandler, FileSystemEvent | |
from watchdog.observers import Observer | |
sys.path.append('plugins') | |
plugins = {} | |
def scan_plugin(path): | |
for filepath in glob(os.path.join(path, '*.py')): | |
load_plugin(filepath) | |
def load_plugin(filepath): | |
filename = os.path.basename(filepath) | |
module_name = os.path.splitext(filename)[0] | |
if module_name not in plugins: | |
plugins[module_name] = import_module(module_name) | |
print('{} loaded.'.format(module_name)) | |
else: | |
plugins[module_name] = reload(plugins[module_name]) | |
print('{} reloaded.'.format(module_name)) | |
class PluginHandler(FileSystemEventHandler): | |
def on_created(self, event: FileSystemEvent): | |
print(event) | |
if event.src_path.endswith('.py'): | |
load_plugin(event.src_path) | |
scan_plugin('plugins') | |
observer = Observer() | |
observer.schedule(PluginHandler(), 'plugins') | |
observer.start() | |
while True: | |
time.sleep(1) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment