Chinaunix首页 | 论坛 | 博客

分类: Python/Ruby

2014-03-11 22:18:12

#! /usr/bin/env python
# ---*--- coding:utf-8 --*---

import os, sys, re
from ConfigParser import *

if __name__ == '__main__':
        if len(sys.argv) !=2:
                print ("I want two parameters, but you give me %d.", len(sys.argv))
                exit(-1)
        filename = sys.argv[1]
        if not os.path.isfile(filename):
                print ("please give me the right file")
                exit(-1)
        parser = ConfigParser()
        parser.read(filename)
        for section in parser.sections():
                for option in parser.options(section):
                        print option, "=", parser.get(section, option)


ConfigParser模块,模块如其名,是用来解析config文件的。该模块对Config文件的要求如下:
[main]  ( [ ] 是section的标志,main是section的名称)
cachedir(这是option)=/var/cache/yum(这是value,字符串类型)
keepcache=1(整数)
debuglevel=2
logfile=/var/log/yum.log
exactarch=1
obsoletes=1.0(float)

ConfigParser 可以有
read、readfp 是打开config文件的操作。
sections、has_section、remove_section是操作section的。
 options、has_option、items、remove_option、remove_option、set 是操作option的。
    items、get、getint、getfloat、getboolean是操作value的。
这些函数没什么可说的,基本上按照字面意义即可理解。


对于commands模块来说
import commands    
outtext = commands.getoutput(cmd)                  # cmd是一个Shell的命令(以字符串形式给出),它产生的标准输出和错误输出都会赋值给outtext。
(exitstatus, outtext) = commands.getstatusoutput(cmd)      #不仅返回shell命令的输出,连带着错误码也返回了。
outtext = commands.getstatus(file)                      # 只返回错误码。


阅读(772) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~