Differences
This shows you the differences between two versions of the page.
— |
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> | ||
+ | / | ||
+ | |||
+ | [colors] | ||
+ | color1=red | ||
+ | color2=blue | ||
+ | </ | ||
+ | |||
+ | ---- | ||
+ | |||
+ | ====== The Code ====== | ||
+ | |||
+ | <code python program-name.py> | ||
+ | # os: Use bash environment variables | ||
+ | import os | ||
+ | |||
+ | # ConfigParser: | ||
+ | import ConfigParser | ||
+ | |||
+ | # New ConfigParser instance called " | ||
+ | config = ConfigParser.ConfigParser() | ||
+ | |||
+ | # Read the Config File | ||
+ | config.read(os.environ.get(' | ||
+ | |||
+ | # Set variables based off of the config file read | ||
+ | my_color1 = config.get(" | ||
+ | my_color2 = config.get(" | ||
+ | |||
+ | # Show gathered settings | ||
+ | print(" | ||
+ | </ | ||
+ | |||
+ | ---- | ||