[[python_wiki:config_parser]]

Config Parser

General Information

Using the config parser module to read external config files.

Checklist

  • import ConfigParser
  • A config file to parse!

Usage

Assume the following example config file for the code example

/home/myuser/.settings/config
 
[colors]
color1=red
color2=blue

The Code

program-name.py
# os: Use bash environment variables
import os
 
# ConfigParser: Use variables from external file
import ConfigParser
 
# New ConfigParser instance called "config"
config = ConfigParser.ConfigParser()
 
# Read the Config File
config.read(os.environ.get('HOME') + "/.settings/config")
 
# Set variables based off of the config file read
my_color1 = config.get("colors", "color1")
my_color2 = config.get("colors", "color2")
 
# Show gathered settings
print("My colors were: %s and %s") % (my_color1, my_color2)

  • python_wiki/config_parser.txt
  • Last modified: 2019/05/26 03:50
  • (external edit)