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

简单介绍:

此模块提供命令行选项解析,目前支持短格式和长格式选项

快速安装:

说明:  内建模块无需安装

解析方法:

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配置文件最终返回字典,方便主程序加载,而并没有在主程序中写死,这样更方便程序的单元测试代码编写和审查.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值