1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Pythonで読み込む設定ファイルを切り替える方法

Last updated at Posted at 2020-09-07

はじめに

Pythonでプログラムを実行する際にオプションをつけることで読み込む設定ファイルを変える方法です。

ファイル構成

.
├── config
│   ├── config_dev.ini
│   └── config_prod.ini
└── main.py

設定ファイル

confg_prod.ini
[MYSQL]
USER = "user_prod"
PWD = "password_prod"
config_dev.ini
[MYSQL]
USER = "user_dev"
PWD = "password_dev"

実行ファイル

main.py
import argparse
import configparser


def parser_conf():
    parser = argparse.ArgumentParser()
    parser.add_argument(
        "-p",
        "--prod",
        action="store_true",
        help="use prod config")
    parser.add_argument(
        "-d",
        "--dev",
        action="store_true",
        help="use dev config")
    args = parser.parse_args()
    config = configparser.ConfigParser()
    if args.prod:
        config_file_name = "config/config_prod.ini"
    else:
        config_file_name = "config/config_dev.ini"
    config.read(config_file_name, encoding='utf-8')
    return config


if __name__ == '__main__':
    config = parser_conf()
    print(config['MYSQL']['USER'])
    print(config['MYSQL']['PWD'])

実行結果

$ python main.py -d
"user_dev"
"password_dev"

$ python main.py --dev
"user_dev"
"password_dev"

$ python main.py -p
"user_prod"
"password_prod"

$ python main.py --prod
"user_prod"
"password_prod"
1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?