python_wiki:config_parser

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

python_wiki:config_parser [2019/05/25 23:50]
python_wiki:config_parser [2019/05/25 23:50] (current)
Line 1: Line 1:
 +====== 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
 +<code bash>
 +/home/myuser/.settings/config
 +
 +[colors]
 +color1=red
 +color2=blue
 +</code>
 +
 +----
 +
 +====== The Code ======
 +
 +<code python 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)
 +</code>
 +
 +----
  
  • python_wiki/config_parser.txt
  • Last modified: 2019/05/25 23:50
  • (external edit)