As I get into the habit of using git and github for versioning I need to make sure that I hide personal settings and passwords. To do this I use ConfigParser in Python. It’s pretty easy.
Creating the Configuration File
First create a ‘config.ini’ file in your code directory. I generally use a text editor or program such as Geany to do this. Section heading are enclosed in square brackets () and parameters are stored in “key = value” pairs.
[Section Heading] setting name 1 = 192.168.0.1 setting name 2 = thisismypassword
To create the file programmatically you can use code such as:
import ConfigParser parser = ConfigParser.SafeConfigParser() parser.add_section('Section Heading') parser.set('Section Heading', 'Setting Name 1' , '192.168.0.1') parser.set('Section Heading', 'Setting Name 2' , 'thisismypassword') with open('config.ini', 'wb') as configfile: parser.write(configfile)
Reading the Configuration File
I typically read the configuration file in the ‘__init__’ method of the class I am building. Alternatively, you can do this at the start of your function or script. The code is as follows:
import ConfigParser parser = ConfigParser.SafeConfigParser() parser.read('config.ini') ip = parser.get('Section Heading', 'Setting Name 1') password = parser.get('Section Heading', 'Setting Name 2')
Ignoring the Configuration File
Finally to prevent the configuration file from being uploaded to github add a ‘.gitignore’ file to the directory with a line saying ‘*.ini’.