Last active
August 29, 2015 14:17
-
-
Save demitri/31ba8d552b58c95735ae to your computer and use it in GitHub Desktop.
Simple example for reading configuration files.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
''' | |
This is a simple example of how to read configuration (or parameter) files in Python | |
using the ConfigParser module. | |
Docs: | |
https://docs.python.org/2.7/library/configparser.html | |
https://docs.python.org/3/library/configparser.html | |
''' | |
# Imagine a separate parameter file called "parameters.cfg". Values are grouped into different (named) domains. | |
# Note strings are not in quotes. | |
''' | |
[simulation time] | |
tot_time = 6 | |
dt = 0.2 | |
time_unit = Gy | |
[timescales] | |
tau_df = 3 | |
t_d = 0 | |
t_ia = 2 | |
time_steps = [1, 2, 3, 4, 5] | |
''' | |
import ConfigParser | |
import json | |
# read the configuration file: | |
params = ConfigParser.ConfigParser() | |
params.read("parameters.cfg") | |
# all values are now in "params" | |
# access values by domain: | |
dt = params.get("simulation time", "dt") | |
time_unit = params.get("simulation time", "time_unit") | |
# Note that it's ok to have spaces in domain names and keywords | |
# The ConfigParser doesn't support arrays directly, but they are too useful | |
# not to have. Instead, we can use a trick by interpreting them as JavaScript strings. | |
time_steps = json.loads(params.get("timescales", "time_steps")) | |
# We can use this step to enforce a particular data type: | |
t_d = float(params.get("timescales", "t_d")) | |
# For simple datatypes (int, float, boolean) though, there are different "get" methods | |
# that do the same thing. | |
t_d = params.getfloat("timescales", "t_d") | |
t_d = params.getint("timescales", "t_d") | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment