settings.py モジュール内で定義されている変数一覧を取得したい Django

2024年6月18日

Pythonで別のモジュールから変数一覧を取得するのは一般的には難しいですが、settings.py モジュール内で定義されている変数を知りたい場合、モジュールを読み込んでその属性を調べることができます。以下は、変数一覧を取得するための簡単な方法です。

python
# settings.py
remote_original_path = '/path/to/remote/original/file.csv'
remote_copy_to_path = '/path/to/remote/copy/to/file.csv'
remote_host = 'example.com'
remote_port = 22
remote_username = 'username'
private_key_path = '/path/to/private/key.pem'
some_variable = 'example_value'

# main_script.py
from settings import *

def get_variable_names(module):
    return [var for var in dir(module) if not callable(getattr(module, var)) and not var.startswith("__")]

if __name__ == "__main__":
    # settings.py の変数一覧を取得
    variable_names = get_variable_names(settings)

    # 取得した変数一覧を表示
    print("Variable names in settings.py:")
    for var_name in variable_names:
        print(var_name)

上記の例では、settings.py モジュール内の変数一覧を取得して表示する get_variable_names 関数を定義しています。この関数を使用することで、settings.py 内の変数一覧を取得できます。ただし、この方法はあくまでモジュールの属性を取得するものであり、変数の値は取得されません。

未分類

Posted by ぼっち