How to read a config file in Python:

This article will help you to read config based on the environment. For example, If you have a python script which uses different database config for UAT and PROD.

[PROD]
host = "192.168.0.1"
port = "12345"
user = "PROD_SCHEMA"
password = "Pwd1"
service = "service_prd.service.com"

[UAT]
host = "192.168.0.2"
port = "12345"
user = "UAT_SCHEMA"
password = "Pwd2"
service = "service_uat.service.com"

config_reader.py

#Python script to read database config from a file.

import ConfigParser

configParser = ConfigParser.RawConfigParser()   
configFilePath = r'F:\database.cfg'
configParser.read(configFilePath)

print("== PROD Config == ")
user = configParser.get('PROD', 'user')
host = configParser.get('PROD', 'host')

print(" User : {0} , Host: {1}". format(user,host))

print("== UAT Config == ")
user = configParser.get('UAT', 'user')
host = configParser.get('UAT', 'host')

print(" User : {0} , Host: {1}". format(user,host))

Output:

 

 

##############

In Python 3, ConfigParser has been renamed to configparser for PEP 8 compliance

(Visited 481 times, 36 visits today)