Mit dieser Methode können Sie die zu lesende Einstellungsdatei ändern, indem Sie beim Ausführen eines Programms in Python eine Option hinzufügen.
.
├── 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"
Recommended Posts