2017-08-07 1 views
0

私はPythonファイルを含むディレクトリ(およびサブディレクトリ)を持っています。各ファイルに含まれるクラスは1つだけです。ディレクトリ内のすべてのモジュールを動的にロードし、Pythonのリストに追加します。

commands = [] 

def load_commands(): 
    for name in os.listdir('/commands'): 
     module = import name 
     for key, value in module: 
      print(key, value) #-> "Ping", ClassObject 
      if isClass(value): 
       commands.append(Value()) #where value is the class 

これはPython3.5で行うことは可能です:

ここでの例では、

commands/ping.py

class Ping: 
    def __init__(): 
     print('works') 

の線に沿って何か私は何をしたいのですか?可能であれば、これを達成する方法についていくつか提案していますか?

答えて

0
import inspect 
import importlib 

def load_commands(self): 
    for directory in os.listdir('{0}/commands/'.format(self._config['root_directory'])): 
     if (directory != "__init__.py" and directory != "__pycache__"): 
      for file in os.listdir('{0}/commands/{1}'.format(self._config['root_directory'], directory)): 
       if (file != "__init__.py" and file != "__pycache__"): 
        path = "commands.{0}.{1}".format(directory, file[:-3]) 
        module = inspect.getmembers(importlib.import_module(path)) 

        for key, value in module: 
         if (inspect.isclass(value) and issubclass(value, Command) and not key == "Command"): 
          self._commander.add(value()) 

私は上記のコードを使用して解決しました。将来誰かが同じことをしたいと思ったらそれを掲示する。

関連する問題