设为首页 收藏本站
查看: 937|回复: 0

[经验分享] python 常用的模块 optparse与ConfigParser

[复制链接]
累计签到:1 天
连续签到:1 天
发表于 2015-11-2 10:59:39 | 显示全部楼层 |阅读模式
一、optparse 模块
  功能:optparse模块用于处理命令行参数
        使用流程:
    1、首先,必须 import OptionParser 类,创建一个 OptionParser 对象:
1
2
3
4
from optparse import OptionParser

def Opt ():
   parser=OptionParser("Usage: %prog -o option -d domain -s subject")



   2、使用 add_option 来定义命令行参数:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
   parser.add_option("-d",
                      "--domain",
                      dest="domain",
                      default=False,
                      action="store_true",
                      help="special domain_name or domain_name/user",)
   parser.add_option("-s",
                      "--subject",
                      dest="subject",
                      default=False,
                      action="store_true",
                      help="special subject for record operational log",)
   parser.add_option("-o",
                      "--operation",
                      dest="operation",
                      default=False,
                      action="store_true",
                      help="special operation Del or Insert Key ",)
   options,args = parser.parse_args()
   return options,args
   #以上是定义参数与选项,返回对象与参数



    选项说明:
     每个命令行参数就是由参数名字符串和参数属性组成的。如 -d 或者 --domain 分别是长短参数名
     dest: 是可选的。如果没有指定 dest 参数,将用命令行的参数名来对 options 对象的值进行存取
     store:有两种形式:store_true和store_false,用于处理带命令行参数后面不带值的情况。如 -v,-q [-v 也可以认为查看版本-q表示退出时后面可以不带值]
     default:可以为参数指定默认值;如果-f表示文件,但没有指定值,那么在解析时会直接找到default定义的默认值。
     action是parse_args()方法的参数之一,它指示optparse当解析到一个命令行参数时该如何处理。actions 有一组固定的值可供选择,默认是'store',表示将命令行参数值保存在 options 对象里。
     help:定义帮助信息,是对参数的描述

   3、生产中使用的完整例子:
    这个脚本的功能其实就是对redis添加删除操作
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
#!/usr/bin/env python
#coding:utf-8
#Date: 2015-09-09
#Author:king.gp
################描述#################
#
#查找是否设置此kye,有则跳过
#如果没有设置此kye,并将操作写入/var/log/redis_add_pause_domain_list.log中
#如果恢复指定的存在的key,也要写入到/var/log/redis_retrieve_pause_domain_list.log
#
####################################

import redis
import datetime
import os
import sys
from optparse import OptionParser

def Opt ():
   parser=OptionParser("Usage: %prog -o option -d domain -s subject")
   parser.add_option("-d",
                      "--domain",
                      dest="domain",
                      default=False,
                      action="store_true",
                      help="special domain_name or domain_name/user",)
   parser.add_option("-s",
                      "--subject",
                      dest="subject",
                      default=False,
                      action="store_true",
                      help="special subject for record operational log",)
   parser.add_option("-o",
                      "--operation",
                      dest="operation",
                      default=False,
                      action="store_true",
                      help="special operation Del or Insert Key ",)
   options,args = parser.parse_args()
   return options,args,parser
   #以上是定义参数与选项,返回对象与参数

def Connect_Redis(options,hostname,parser,*argv):
   r = redis.Redis(host='localhost',port=6379,db='0')
   if options.domain:
     key_string = hostname+'/Conf/MailBox/'+argv[1]+'/Status_Pause_All'
     key_list=r.keys(key_string)
     if (options.operation and  argv[0]=='search'):
       if len(key_list) > 0 :
         print key_list[0]+' Existing'
       else:
         print key_string+' Not Existing'
       sys.exit(0)   

     if (options.operation and options.subject and argv[0]=='delete'):
        if  len(key_list)>0:
           r.delete(key_string)
         #print key_string
           print key_string+' alrealy Del!'
           with open('/var/log/redis_retrieve_pause_domain_list.log','a') as f:
             now = datetime.datetime.now()  
             date_string = now.strftime("%Y-%m-%d %H:%M:%S")
             f.write(date_string+'\t'+argv[2]+'\t'+key_string+'\n')
           sys.exit(0)
        else:
           print key_string+' Not Existing'
           sys.exit(0)
     elif (options.operation and options.subject and argv[0] =='insert'):
          r.set(key_string,'1')
          print key_string+' alrealy Set!'
          with open('/var/log/redis_add_pause_domain_list.log','a') as f:
            now = datetime.datetime.now()  
            date_string = now.strftime("%Y-%m-%d %H:%M:%S")
            f.write(date_string+'\t'+argv[2]+'\t'+key_string+'\n')
          sys.exit(0)
     else:
        parser.error("domain or subject not empty")

   else:
      sys.exit(0)

def Get_Host_Name():
  host = os.popen('echo $HOSTNAME')
  hostname = host.read().strip()
  if len(hostname) > 4:
    hostname = hostname.split('.')[0]
  return hostname

def main():
    options,args,parser=Opt()
    if args:
      keys=tuple(args)
      hostname=Get_Host_Name()
      Connect_Redis(options,hostname,parser,*keys)
    else :
      parser.error("Usage: %prog -o option -d domain -s subject")
     
if __name__ == '__main__':
    main()



  4、查看帮助
1
2
3
4
5
6
7
8
[iyunv@mx1 yunwei]# python change_redis_pause_key.py  -h
Usage: change_redis_pause_key.py -o option -d domain -s subject

Options:
  -h, --help       show this help message and exit
  -d, --domain     special domain_name or domain_name/user
  -s, --subject    special subject for record operational log
  -o, --operation  special operation Del or Insert Key



二、ConfigParser模块
  1、功能:配置文件解析模块【我是这么理解的】
  2、说明:配置文件要mysql的配置文件一样分区段;配置文件的格式:中括号“[ ]”内包含的为section。section 下面为类似于key-value 的配置内容。
      3、函数说明:

    • 读取配置文件时的函数

1
2
3
4
5
6
read(filename) 直接读取ini文件内容
sections() 得到所有的section,并以列表的形式返回
options(section) 得到该section的所有option
items(section) 得到该section的所有键值对
get(section,option) 得到section中option的值,返回为string类型
getint(section,option) 得到section中option的值,返回为int类型,还有相应的getboolean()和getfloat() 函数。




    • 写入文件时的函数

1
2
add_section(section) 添加一个新的section
set( section, option, value) 对section中的option进行设置,需要调用write将内容写入配置文件。




    • 保存文件


1
conf.write(open(network_path+network_card,'w'))



  4、写个例子
   说明:迁移机房生成原IP与新IP的绑定到对应的配置文件中
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
bash-4.1$ cat network.py
#!/usr/bin/env python
#conding:utf8

#
import sys
import os
import commands
import ConfigParser

class Netconf(ConfigParser.ConfigParser):
    def __init__(self,default=None):
       ConfigParser.ConfigParser.__init__(self,defaults=None)
    def optionxform(self,optionstr):
       return optionstr

def Def_Network(source_ip,network_card):
    str_card=network_card[:10]+'\\'+network_card[10:] #定义DEVICE:eth0:x
    network_path='/home/sysadmin/proxy_config/'
    network_template='ifcfg-ethx'
    network_full_path=network_path+network_template
    conf=Netconf()
    conf.read(network_full_path)
    conf.set("network_card","IPADDR",source_ip)
    conf.set("network_card","DEVICE",network_card[6:])
    conf.write(open(network_path+network_card,'w'))
    cmd ="sed -i 's@ @@g' "+network_path+str_card
    (s,r)=commands.getstatusoutput(cmd)
    if s ==0:
      print "Success"
      #['ipv6init', 'userctl', 'dns2', 'dns1', 'ipaddr', 'onboot', 'netmask', 'device', 'type', 'gateway']

def main():
  source_file='/home/sysadmin/proxy_config/unix_proxy.txt'
  if os.path.exists(source_file):
     with open(source_file) as fn:
        data = fn.readlines()
        #print type(data)
        for ethx  in data:
           ethx=ethx.split('\t')
           C_IP=ethx[0].strip()
           N_IP=ethx[1].strip()
           W_Card=ethx[2].strip()
           Def_Network(C_IP,W_Card)   
  else:   
    print " %s file not found" %source_file


if __name__=='__main__':
    main()



注:遇到的问题,可能在其它服务的配置文件里不算什么问题,但是,在网卡设置中这是一个大的问题

    • 参数的大小写;ConfigParser模块中将所有读取的Key都变成了小写,而网卡的配置文件必须是大写;请查看ConfigParser模块的文件【我的是centos6.3x86_64系统,环境python2.6.6,路径为

/usr/lib64/python2.6/ConfigParser.py】
   如果要解决这个问题有两种方式:
     第一:要修改ConfigParser.py文件中的将return optinostr.lower()改成return optionstr即可。
1
2
354     def optionxform(self, optionstr):
355         return optionstr.lower()



     第二:通过类继承,重写optionxfrom方法。
     至于使用那种方法,请根据实际情况而定。

    • 生成的配置文件中,key = value等号两端有空格,配置文件不认,只好用sed命令替换了

  5、原文件unix_proxy
1
2
1.2.3.4  192.168.2.4   ifcfg-eth0:0
5.6.7.8  192.168.2.8   ifcfg-eth0:1



  6、模板文件ifcfg-ethx
1
2
3
4
5
6
7
8
9
10
[network_card]
DEVICE=eth0
ONBOOT=yes
TYPE=Ethernet
IPADDR=1.2.3.4
NETMASK=255.255.254.0
DNS2=1.2.4.8
GATEWAY=1.2.3.1
IPV6INIT=no
USERCTL=no



运行脚本即可绑定网卡的配置文件

三、总结
1、要多写,多看【标准库】这里有中文版本的,有能力的小伙伴可以去试着翻译一下 http://python.usyiyi.cn/python_278/tutorial/index.html
2、承认自己的不足,才能进步
3、多总结


运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-134005-1-1.html 上篇帖子: python迭代器,生成器 下篇帖子: Python中直接在MySQL执行SQL命令 python
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表