您的位置:首页 > 编程语言 > Python开发

基础入门_Python-模块和包.运维开发中内建模块getopt的最佳实践?

2016-09-28 10:23 806 查看
简单介绍:
此模块提供命令行选项解析,目前支持短格式和长格式选项

快速安装:
说明: 内建模块无需安装

解析方法:
getopt(args, shortopts, longopts = []) -> (opts, args)
说明: args为要解析的参数序列,常为sys.argv[1:],shortopts为单字符选项定义串,如果某个选项需要一个参数,响应字母后面必须有一个冒号,longopts为长格式的选项名序列,可以包含多个字符,序列元素必须包含--前缀,如果此长选项需要参数则其名应包含后缀=,而且短格式和长格式可以在调用中结合使用,最终返回一个选项元组序列opts和非选项元组序列args

应用场景:
1. 规范化的程序目录结构及代码风格推荐我们程序配置从外部加载,不要写死,想想运维中nginx/mysql等应用都是利用getopt解析命令行参数?
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
#
# Authors: limanman
# OsChina: http://xmdevops.blog.51cto.com/ # Purpose:
#
"""
# 说明: 导入公共模块
import os
import sys
import getopt
import ConfigParser
# 说明: 导入其它模块

program = __file__
version = '1.0.0.1'

# 说明: 显示使用说明
def show_usage_info():
message = '''%s version: %s/%s
Usage: xmzoomeye-agent [-hv] [-c filename] [-l filename]

Options:
-h      : this help
-v      : show version and exit
-c      : set running configuration file (default: docs/default.ini)
-l      : set logging configuration file (default: docs/logging.ini)
''' % (program, program, version)
print message

# 说明: 检测参数指定
def parameters_test():
try:
opts, args = getopt.getopt(sys.argv[1:], 'hvc:l:', [])
except getopt.GetoptError, e:
print '%s: %s' % (program, e)
sys.exit()

exit_flag = [0, 0, 0]
for key, val in opts:
if '-v' == key:
print 'version: %s/%s' % (program, version)
exit_flag[0] = 1
if '-h' == key:
show_usage_info()
exit_flag[0] = 1
if '-c' == key:
exit_flag[1] = 1
if '-l' == key:
exit_flag[2] = 1
if exit_flag[0]:
sys.exit()
if not all(exit_flag[1:]):
print '%s: option -c/-l requires arguments' % (program,)
sys.exit()
return dict(opts)

# 说明: 检测配置文件
def configuration_test(opts):
cf = {}
cp = ConfigParser.ConfigParser()

for opt, arg in opts.iteritems():
if not os.path.exists(arg):
print '%s: no such config file %s' % (program, arg)
sys.exit()

runconfig = os.path.abspath(opts['-c'])
with open(runconfig, 'r+b') as handler:
cp.readfp(handler, runconfig)
sections = cp.sections()
if 'redis' not in sections or 'agent' not in sections:
print '%s: no redis and agent section' % (program,)
sys.exit()
for section in sections:
if section not in cf:
cf.setdefault(section, {})
cf[section].update(cp.items(section))
return cf

if __name__ == '__main__':
pass
说明: 如上案例简单的利用getopt解析命令行参数,利用ConfigParser解析ini配置文件最终返回字典,方便主程序加载,而并没有在主程序中写死,这样更方便程序的单元测试代码编写和审查.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Python 基础入门