What is the most pythonic method for specifying a configuration file?

I am writing a daemon script in Python and would like to specify the parameters in the file that the program expects to read (e.g. .conf files). The standard library has configparser and xdrlib file formats, but none of them seem pythonic; the first of which is the Microsoft standard, and the second is the Sun Microsystems standard.

I could write my own, but I would rather use a well-known and documented standard than reinvent the wheel.

+6
source share
3 answers

IMHO: NEVER touch the ConfigParser module, its obsolete (reads: obviously, not updated) and has quite a few quirks. API for comments? Forget it! Access to the section DEFAULT section? Lol! Interested in unassembled Config-Fields? Well guess that: ConfigParser iterates over all your configuration files and fails (obscures), perhaps EVENTUALLY makes a compressed Exception-Trace over ALL Errors. It is not easy to figure out which error belongs to the file. No nested configuration sections ...

Rather, CSV, and then ConfigParser!

IMO: use Json for configuration files. A very flexible, direct mapping between python data structures and the Json-String representation is possible and still accessible to people. Btw. the exchange between different languages ​​is quite simple.

Curly-Braces in a file is not so pretty, but you can't do everything !; -)

+2
source

If you have no particular difficulties, there is nothing wrong with using configparser. This is a simple, flat file format that is easy to understand and familiar to many people. If this really spoils you the wrong way, there is always the option to use the JSON or YAML configuration, but these are somewhat more difficult formats.

A third popular option is to simply use Python for your configuration file. This gives you more flexibility, but also increases the likelihood of introducing strange errors by β€œjust” modifying your configuration file.

+5
source

I started with configparser and optionsparser, but for me the easiest way is to simply define the dictionaries in the .py file and import it as a module. Then you can directly access the configurations without further processing.

# # example.py # config = { "dialect" : "sqlite", "driver" : "", "database" : "testdb", "host" : "localhost", "port" : "0" } 

where you need access, just do:

 from example import config print config["database"] 
+1
source

All Articles