Analysis of the actual application of the Python configuration file

Source: Internet
Author: User

You can use the following articles to better understand the Python configuration file, I hope you will give a brief introduction to its simple application in computer language. The following articles will introduce it in detail.

It is common to use a configuration file in a program to flexibly configure some parameters. The parsing of configuration files is not complicated, especially in python, the officially released library contains the library for doing this, that is, ConfigParser. Here is a brief introduction. The format of the configuration file parsed by ConfigParser is similar to that of the ini configuration file, which consists of multiple sections. Each section has multiple configuration items, for example:

 
 
  1. [db]   
  2. db_host=127.0.0.1   
  3. db_port=3306   
  4. db_user=root   
  5. db_pass=password   
  6. [concurrent]   
  7. thread=10   
  8. processor=20  

Assume that the configuration file above is named test. conf. It contains two sections, one is db, the other is concurrent, the db also contains four items, and the concurrent contains two items. Here we will do the parsing:

 
 
  1. #-*- encoding: gb2312 -*-   
  2. import ConfigParser   
  3. import string, os, sys   
  4. cf = ConfigParser.ConfigParser()   
  5. cf.read("test.conf")    

Returns all sections.

 
 
  1. s = cf.sections()   
  2. print 'section:', s   
  3. o = cf.options("db")   
  4. print 'options:', o   
  5. v = cf.items("db")   
  6. print 'db:', v   
  7. print '-'*60   

Can be read by type

 
 
  1. db_host = cf.get("db", "db_host")   
  2. db_port = cf.getint("db", "db_port")   
  3. db_user = cf.get("db", "db_user")   
  4. db_pass = cf.get("db", "db_pass")  

The returned value is an integer. The above content is an introduction to the Python configuration file.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.