Skip to content

Instantly share code, notes, and snippets.

@tag1216
Created July 14, 2017 14:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tag1216/66d3c167c9f7e319a5af5e1639639663 to your computer and use it in GitHub Desktop.
Save tag1216/66d3c167c9f7e319a5af5e1639639663 to your computer and use it in GitHub Desktop.
ディレクトリ内のPythonモジュールを動的インポート/リロード
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