易截截图软件、单文件、免安装、纯绿色、仅160KB

python模块之ConfigParser: 用python解析配置文件

在程序中使用配置文件来灵活的配置一些参数是一件很常见的事情,配置文件的解析并不复杂,在python里更是如此,在官方发布的库中就包含有做这件事情
的库,那就是ConfigParser,这里简单的做一些介绍。
   
ConfigParser解析的配置文件的格式比较象ini的配置文件格式,就是文件中由多个section构成,每个section下又有多个配置项,
比如:
[db]
db_host=127.0.0.1
db_port=3306
db_user=root
db_pass=password
[concurrent]
thread=10
processor=20
假设上面的配置文件的名字为test.conf。里面包含两个section,一个是db, 另一个是concurrent,
db里面还包含有4项,concurrent里面有两项。这里来做做解析:
#-*- encoding: gb2312 -*-
import ConfigParser
import string, os, sys

cf = ConfigParser.ConfigParser()
cf.read("test.conf")
# 返回所有的section
s = cf.sections()
print 'section:', s

o = cf.options("db")
print 'options:', o

v = cf.items("db")
print 'db:', v

print '-'*60
#可以按照类型读取出来
db_host = cf.get("db", "db_host")
db_port = cf.getint("db", "db_port")
db_user = cf.get("db", "db_user")
db_pass = cf.get("db", "db_pass")

# 返回的是整型的
threads = cf.getint("concurrent", "thread")
processors = cf.getint("concurrent", "processor")

print "db_host:", db_host
print "db_port:", db_port
print "db_user:", db_user
print "db_pass:", db_pass

print "thread:", threads
print "processor:", processors
#修改一个值,再写回去
cf.set("db", "db_pass", "zhaowei")
cf.write(open("test.conf", "w"))


相关文档:

Python学习笔记 文件读写

Python中文件操作可以通过open函数,这的确很像C语言中的fopen。通过open函数获取一个file object,然后调用read(),write()等方法对文件进行读写操作。
1.open
使用open打开文件后一定要记得调用文件对象的close()方法。比如可以用try/finally语句来确保最后能关闭文件。
file_object = open('thefile.txt') ......

Python执行系统命令的方法

Python中执行系统命令常见方法有两种:
两者均需 import os
(1) os.system
# 仅仅在一个子终端运行系统命令,而不能获取命令执行后的返回信息
system(command) -> exit_status   
Execute the command (a string) in a subshell. 
# 如果再命令行下执行,结果直接打印出来
>>> os. ......

Python日期和字符串的互转

用的分别是time和datetime函数
'''
Created on 2009-9-2
@author: jiangqh
'''
import time,datetime
# date to str
print time.strftime("%Y-%m-%d %X", time.localtime())
#str to date
t = time.strptime("2009 - 08 - 08", "%Y - %m - %d")
y,m,d = t[0:3]
print datetime.datetime(y,m,d)

输出当前时间 ......

关于Python中一种回调方式的实现

#关于回调功能的测试
#Functor是这种回调功能的关键对象
class Functor:
    """Simple functor class."""
    def __init__( self, fn, *args ):
        self.fn = fn
        ......

python的灵活

项目需要,刚刚接触python。
今天看书看到a>b==c ,a,b,c为integer
在C/C++/C#中,a>b为boolean,不可与integer比较相等
但python a>b==c等效于((a>b)&&(b==c))
在python中的写法是a>b and b==c ......
© 2009 ej38.com All Rights Reserved. 关于E健网联系我们 | 站点地图 | 赣ICP备09004571号