Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Write comment in config files with python

I need to write some comment in a configuration file generated at runtime via ConfigParser library in Python.

I want to write a full descriptive comment like:

########################
# FOOBAR section 
# do something 
########################
[foobar]
bar = 1
foo = hallo

The code should look like:

Where I insert comment and configurations options in the same moment.

import ConfigParser

config = ConfigParser.ConfigParser()

config.insert_comment("##########################") # This function is purely hypothetical 
config.insert_comment("# FOOBAR section ")
....

config.add_section('foobar')
config.set('foobar', 'bar', '1')
config.set('foobar', 'foo', 'hallo')
like image 310
Giggi Avatar asked Oct 12 '12 06:10

Giggi


People also ask

How do I comment in config file in Python?

To enter comments in a configuration file, use a comment character and enter the comment text anywhere to the right of the comment character on the same line.

How do I comment in web config?

Select the lines you want to be commented in your ASPX, HTML, web config file etc and click on the Comment/ Uncomment icon in Toolbar. Alternatively you can use Keyboard shortcut Ctrl+K Ctrl+C to comment and use Ctrl+K Ctrl+U to uncomment.

How do you add a configuration in Python?

Configuration tab Click the list to select a type of target to run. Then, in the corresponding field, specify the path to the Python script or the module name to be executed. In this field, specify parameters to be passed to the Python script.


1 Answers

From the docs:

Lines beginning with '#' or ';' are ignored and may be used to provide comments.

Configuration files may include comments, prefixed by specific characters (# and ;). Comments may appear on their own in an otherwise empty line, or may be entered in lines holding values or section names. In the latter case, they need to be preceded by a whitespace character to be recognized as a comment. (For backwards compatibility, only ; starts an inline comment, while # does not.)

Examples:

conf.set('default_settings', '; comment here', '')

or

[default_settings]
    ; comment here = 
    test = 1

config = ConfigParser.ConfigParser()
config.read('config.ini')
print config.items('default_settings')

>>>
[('test','1')] # as you see comment is not parsed
like image 170
root Avatar answered Sep 25 '22 04:09

root