Skip to content

Instantly share code, notes, and snippets.

@dogrunjp
Last active December 11, 2015 03:37
Show Gist options
  • Save dogrunjp/c9c53a80f8889ba87f99 to your computer and use it in GitHub Desktop.
Save dogrunjp/c9c53a80f8889ba87f99 to your computer and use it in GitHub Desktop.
Pythonで実行するモジュールを動的に変更したいとき

Pythonで実行する処理のモジュールを動的に変更したいとき

test_module_1.py

def test():
    print('モジュール1です')

こんな感じに、同じ関数名で処理内容の違うモジュールを何らかの変数によって選択して実行したい場合のPythonの記法を考えてみました。

わかりやすく、スクリプトのコマンドライン引数で呼び出したいモジュールを変更するケースを考えてみます。

import sys
import modules.test_module_1
import modules.test_module_2

argvs = sys.argv

OPTIONS = {
    "01": modules.test_module_1,
    "02": modules.test_module_2
}

if __name__ == '__main__':
    OPTIONS[argvs[1]].test()

これをCLで下のように実行するとOPTIONSに登録されたモジュールが呼び出されて、それぞれのtest()が実行されます。

$ python test.py 01

もっと、シンプルな書き方もありそうだけどこれはこれで見通しよくてOKな気もしています。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment