Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading array from config file in python

I have a problem. My program is using config file to set options, and one of those options is a tuple. Here's what i mean:

[common]
logfile=log.txt
db_host=localhost
db_user=root
db_pass=password
folder[1]=/home/scorpil
folder[2]=/media/sda5/
folder[3]=/media/sdb5/

etc... Can i parse this into tuple with ConfigParser module in Python? Is there some easy way to do this?

like image 373
Scorpil Avatar asked Nov 04 '10 13:11

Scorpil


People also ask

What is config parser in Python?

Source code: Lib/configparser.py. This module provides the ConfigParser class which implements a basic configuration language which provides a structure similar to what's found in Microsoft Windows INI files.

What is INI file in Python?

An INI file is a configuration file for computer software that consists of a text-based content with a structure and syntax comprising key–value pairs for properties, and sections that organize the properties.


4 Answers

if you can change config format like this:

folder = /home/scorpil
         /media/sda5/
         /media/sdb5/

then in python:

config.get("common", "folder").split("\n")
like image 192
Alex Avatar answered Sep 30 '22 14:09

Alex


Your config could be:

[common]
logfile=log.txt
db_host=localhost
db_user=root
db_pass=password
folder = ("/home/scorpil", "/media/sda5/", "/media/sdb5/")

Assuming that you have config in a file named foo.cfg, you can do the following:

import ConfigParser
cp = ConfigParser.ConfigParser()
cp.read("foo.cfg")
folder = eval(cp.get("common", "folder"), {}, {})

print folder
print type(folder)

which should produce:

('/home/scorpil', '/media/sda5/', '/media/sdb5/')
<type 'tuple'>

-- EDIT -- I've since changed my mind about this, and would take the position today that using eval in this context is a bad idea. Even with a restricted environment, if the configuration file is under user control it may be a very bad idea. Today I'd probably recommend doing something interesting with split to avoid malicious code execution.

like image 21
John Percival Hackworth Avatar answered Sep 30 '22 15:09

John Percival Hackworth


You can get the items list and use a list comprehension to create a list of all the items which name starts with a defined prefix, in your case folder

folders = tuple([ item[1] for item in configparser.items() if item[0].startswith("folder")])
like image 32
Rod Avatar answered Sep 30 '22 15:09

Rod


Create configuration:

folders = ['/home/scorpil', '/media/sda5/', '/media/sdb5/']
config.set('common', 'folders', json.dumps(folders))

Load configuration:

tuple(json.loads(config.get('common', 'folders')))
like image 21
Tai Avatar answered Sep 30 '22 14:09

Tai