写没有操作界面的程序时,最讨厌的就是参数解析问题,尤其是很多参数那种,下面是一个小Demo,拿出来与各位分享:

 # -*- coding:utf8 -*-
import os
import datetime
import sys
from optparse import OptionParser def get_user_paras():
try:
opt = OptionParser()
opt.add_option('--host_ip',
dest='host_ip',
type=str,
help='the ip of the check host')
opt.add_option('--run',
action="store_true",
dest="is_run",
default=False,
help="run the scripts")
opt.add_option('--view',
action="store_false",
dest="is_run",
default=False,
help="only view but not run the scripts")
opt.add_option('--show_type',
dest="show_type",
type=int,
default=0,
help="0 or 1, 0 only show the simple data, 1 show the full data")
(options, args) = opt.parse_args()
is_valid_paras = True
error_messages = []
host_ip = options.host_ip
is_run = options.is_run
show_type = options.show_type
if not host_ip:
error_messages.append("host_ip must be set;")
is_valid_paras = False
if show_type not in [0, 1]:
error_messages.append("show_type only can be 0 or 1;")
is_valid_paras = False if is_valid_paras:
user_paras = {"host_ip": host_ip, "is_run": is_run, "show_type": show_type}
return user_paras
else:
for error_message in error_messages:
print(error_message)
opt.print_help()
return None
except Exception as ex:
print("exception :{0}".format(str(ex)))
return None def main():
user_paras = get_user_paras()
if user_paras is None:
sys.exit(0)
info = "host_ip:{0}, is_run:{1}, show_type:{2}"
info = info.format(user_paras["host_ip"],
user_paras["is_run"],
user_paras["show_type"])
print(info) if __name__ == '__main__':
main()

当使用OptionParser时,会自动增加--help和-h参数,也会自动生成参数帮助,如:

对于代码:

opt.add_option('--run',
action="store_true",
dest="is_run",
default=False,
help="run the scripts")

--run 表示参数名

action表示将参数值如何处理,常用的有store/store_true/store_false,store即字面意思,store_true即将True作为参数值传递给参数,store_false将False作为参数值传递给参数

dest表示命令行参数解析后的参数名,

上面代码中--run作为命令行参数传递进来,由于action为store_true,因此参数值为True,解析后的参数名为is_run,通过(options, args) = opt.parse_args() 赋值后,便可以使用options.is_run来放问参数值。

更多帮助:https://docs.python.org/2/library/optparse.html

##========================================================##

对于参数较多或者参数值较大的情况,个人还是比较喜欢使用参数配置文件来实现,简单而且方便编辑,如创建一个run_config.py文件:

# -*- coding:utf8 -*-

# run config
class RunConfig(object):
is_run = True
show_status = 1
host_ip = "192.167.1.1"
run_scripts = """
SELECT *
FROM TB001
WHERE ID >1000
AND C1<300
"""

然后在其他文件中访问:

# -*- coding:utf8 -*-
from run_config import RunConfig def main():
print("is_run:{0}, host_ip:{1}".format(RunConfig.is_run,RunConfig.host_ip))
print("run_scripts:{0}".format(RunConfig.run_scripts)) if __name__ == '__main__':
main()

简单粗暴,没那么麻烦,土豹子的做法哈!

##===================================================##

Python--命令行参数解析Demo的更多相关文章

  1. Python命令行参数解析模块getopt使用实例

    Python命令行参数解析模块getopt使用实例 这篇文章主要介绍了Python命令行参数解析模块getopt使用实例,本文讲解了使用语法格式.短选项参数实例.长选项参数实例等内容,需要的朋友可以参 ...

  2. python命令行参数解析OptionParser类用法实例

    python命令行参数解析OptionParser类用法实例 本文实例讲述了python命令行参数解析OptionParser类的用法,分享给大家供大家参考. 具体代码如下:     from opt ...

  3. python命令行参数解析模块argparse和docopt

    http://blog.csdn.net/pipisorry/article/details/53046471 还有其他两个模块实现这一功能,getopt(等同于C语言中的getopt())和弃用的o ...

  4. Python 命令行参数解析

    方法1: Python有一个类可以专门处理命令行参数,先看代码: #!/usr/bin/env python # encoding: utf-8 from optparse import Option ...

  5. Python命令行参数解析模块argparse

    当写一个Python脚本时经常会遇到不同参数不同功能的情况,如何做一个更好看的命令帮助信息以及对命令参数解析呢? 这就需要使用argparse模块 #!/usr/bin/env python # -* ...

  6. Python 命令行参数解析工具 argparse

    为什么需要argparse 开门见山,举一个简易计算器代码的例子,其中sys.argv用来读取脚本执行时后面传入的参数. def calculator(x, y, operation): if &qu ...

  7. Python 中命令行参数解析工具 docopt 安装和应用

    什么是 docopt? 1.docopt 是一种 Python 编写的命令行执行脚本的交互语言. 它是一种语言! 它是一种语言! 它是一种语言! 2.使用这种语言可以在自己的脚本中,添加一些规则限制. ...

  8. $命令行参数解析模块argparse的用法

    argparse是python内置的命令行参数解析模块,可以用来为程序配置功能丰富的命令行参数,方便使用,本文总结一下其基本用法. 测试脚本 把以下脚本存在argtest.py文件中: # codin ...

  9. gflags命令行参数解析

    gflags库是google开源的命令行参数解析工具. 安装 官方没有提供二进制库,但是Debian/Ubuntu平台本身提供了二进制库,可以直接git clone https://github.co ...

随机推荐

  1. sprintf()函数,把数字转换成字符串

    char str_2[10];     int a=1234321;     sprintf(str_2,"%d",a);

  2. 在Xcode中使用Git进行源码版本控制

    http://www.cocoachina.com/ios/20140524/8536.html 资讯 论坛 代码 工具 招聘 CVP 外快 博客new 登录| 注册   iOS开发 Swift Ap ...

  3. hibernate的update() 更新延迟或者无法更新,导致同个service调用存储过程执行方法不精确

    hibernate的update()方法无法更新,不报错 原因是hibernate的update方法操作的是缓存,可以flush下先. 设置缓存为false理论上也可. 在一个serivce方法里,执 ...

  4. sublime text3 less2css rem

    1.下载sublime text3 官网地址:https://www.baidu.com/link?url=2kr0ijQXVL1_6oXdPByYh7ecMl7OUAYVx5fyTNjMrYVdtq ...

  5. 再次完善了 WASPCN for Matlab

    前段时间有多个网友询问在64位Matlab中如何使用WASPCN(水和蒸汽性质计算软件)的方法,一直没能给出解决方案. 最近自己有个项目也需要在64位Matlab中如何使用WASPCN(水和蒸汽性质计 ...

  6. 上传App Store成功后,无法构建版本解决方法

    最近iOS10出来了,Xcode也跟着升级到了8,想着App做个更新,于是修改好了代码打算上传新包,无奈总是发现构建不了新版本.这种情况是因为苹果更重视用户的隐私,知道原因就能想到对策了,就是在pli ...

  7. html input的file文件输入框onchange事件触发一次失效解决方法

    最近在做一个图片上传的功能,出现提交一次后,file输入框的change事件无法再次触发的bug,就是说提交一次后必须刷新才能再次提交,这就坑了~ 于是想办法解决它~ 在网上找了一些资料,找到这几种方 ...

  8. Mysql主从架构的复制原理及配置详解

    一.简述Mysql复制 Mysql复制是通过将mysql的某一台主机的数据复制到其他主机(slaves)上,并且在slaves上重新执行一遍来实现.主服务器每次数据操作都会将更新记录到二进制日志文件, ...

  9. I2C VHDL程序

    http://blog.sina.com.cn/s/blog_9bd80b7601012o9y.html library ieee ; use ieee.std_logic_1164.all ; us ...

  10. 我与solr(一)--solr的配置与安装

    感谢upxiaofeng的分享,转载自http://blog.csdn.net/zoubf/article/details/51505940 准备工作: 目前最新版本6.0.下载solr 6.0:So ...