当前位置: 首页 > news >正文

Python--命令行参数解析Demo

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

 1 # -*- coding:utf8 -*-
 2 import os
 3 import datetime
 4 import sys
 5 from optparse import OptionParser
 6 
 7 
 8 def get_user_paras():
 9     try:
10         opt = OptionParser()
11         opt.add_option('--host_ip',
12                        dest='host_ip',
13                        type=str,
14                        help='the ip of the check host')
15         opt.add_option('--run',
16                        action="store_true",
17                        dest="is_run",
18                        default=False,
19                        help="run the scripts")
20         opt.add_option('--view',
21                        action="store_false",
22                        dest="is_run",
23                        default=False,
24                        help="only view but not run the scripts")
25         opt.add_option('--show_type',
26                        dest="show_type",
27                        type=int,
28                        default=0,
29                        help="0 or 1, 0 only show the simple data, 1 show the full data")
30         (options, args) = opt.parse_args()
31         is_valid_paras = True
32         error_messages = []
33         host_ip = options.host_ip
34         is_run = options.is_run
35         show_type = options.show_type
36         if not host_ip:
37             error_messages.append("host_ip must be set;")
38             is_valid_paras = False
39         if show_type not in [0, 1]:
40             error_messages.append("show_type only can be 0 or 1;")
41             is_valid_paras = False
42 
43         if is_valid_paras:
44             user_paras = {"host_ip": host_ip, "is_run": is_run, "show_type": show_type}
45             return user_paras
46         else:
47             for error_message in error_messages:
48                 print(error_message)
opt.print_help()
49 return None 50 except Exception as ex: 51 print("exception :{0}".format(str(ex))) 52 return None 53 54 55 def main(): 56 user_paras = get_user_paras() 57 if user_paras is None: 58 sys.exit(0) 59 info = "host_ip:{0}, is_run:{1}, show_type:{2}" 60 info = info.format(user_paras["host_ip"], 61 user_paras["is_run"], 62 user_paras["show_type"]) 63 print(info) 64 65 66 if __name__ == '__main__': 67 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()

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

 

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

 

相关文章:

  • 股票基本名词概念
  • CSS3动画特效——transform详解
  • 词典建立过程缓慢的解决~~子系统构架重新设计!
  • Angular通过CORS实现跨域方案
  • Outlook Express的邮件导入和邮件导出(备份)
  • 高考过后
  • 路由器知识
  • [英语阅读笔记]Using Page Methods in ASP.NET AJAX
  • 设计模式学习笔记(三:装饰模式)
  • 釜底抽薪:用autoruns揪出流氓软件的驱动保护
  • IT培训Linux文件的复制、删除和移动命令
  • nested exception is org.hibernate.HibernateException: No Session found for current thread
  • SAP BC404 课程中文自学笔记
  • 我的老师孔庆东
  • MS SQL入门基础:SQL数据库表的修改
  • 《网管员必读——网络组建》(第2版)电子课件下载
  • 2017届校招提前批面试回顾
  • Angular 响应式表单 基础例子
  • CEF与代理
  • css的样式优先级
  • git 常用命令
  • Javascript设计模式学习之Observer(观察者)模式
  • js正则,这点儿就够用了
  • MYSQL如何对数据进行自动化升级--以如果某数据表存在并且某字段不存在时则执行更新操作为例...
  • OpenStack安装流程(juno版)- 添加网络服务(neutron)- controller节点
  • Otto开发初探——微服务依赖管理新利器
  • V4L2视频输入框架概述
  • WePY 在小程序性能调优上做出的探究
  • Xmanager 远程桌面 CentOS 7
  • 第十八天-企业应用架构模式-基本模式
  • 对话:中国为什么有前途/ 写给中国的经济学
  • 解析带emoji和链接的聊天系统消息
  • 聚簇索引和非聚簇索引
  • 微信小程序上拉加载:onReachBottom详解+设置触发距离
  • 项目管理碎碎念系列之一:干系人管理
  • 好程序员web前端教程分享CSS不同元素margin的计算 ...
  • ​DB-Engines 11月数据库排名:PostgreSQL坐稳同期涨幅榜冠军宝座
  • (3)选择元素——(14)接触DOM元素(Accessing DOM elements)
  • (C++17) optional的使用
  • (Python第六天)文件处理
  • (博弈 sg入门)kiki's game -- hdu -- 2147
  • (附源码)spring boot校园拼车微信小程序 毕业设计 091617
  • (每日持续更新)jdk api之FileReader基础、应用、实战
  • (三十五)大数据实战——Superset可视化平台搭建
  • (十)c52学习之旅-定时器实验
  • (算法)Game
  • (五)关系数据库标准语言SQL
  • (已解决)什么是vue导航守卫
  • .locked1、locked勒索病毒解密方法|勒索病毒解决|勒索病毒恢复|数据库修复
  • .NET Core、DNX、DNU、DNVM、MVC6学习资料
  • .net oracle 连接超时_Mysql连接数据库异常汇总【必收藏】
  • .net 按比例显示图片的缩略图
  • .NET/C# 编译期间能确定的相同字符串,在运行期间是相同的实例
  • .NET/C# 中你可以在代码中写多个 Main 函数,然后按需要随时切换
  • @FeignClient 调用另一个服务的test环境,实际上却调用了另一个环境testone的接口,这其中牵扯到k8s容器外容器内的问题,注册到eureka上的是容器外的旧版本...