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参数,也会自动生成参数帮助,如:

Python--命令行参数解析Demo第1张

对于代码:

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第2张

免责声明:文章转载自《Python--命令行参数解析Demo》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇Android UI,界面辅助设置工具,可随意拖动控件,比google官方提供的方便Entity Framework 数据库先行、模型先行、代码先行下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

Python强大的可变参数传递机制

今天模拟定义map函数.写着写着就发现Python可变长度参数的机制真是灵活而强大. 假设有一个元组t,包含n个成员: t=(arg1,...,argn) 而一个函数f恰好能接受n个参数: f(arg1,...,argn) f(t)这种做法显然是错的,那么如何把t的各成员作为独立的参数传给f,以便达到f(arg1,...,argn)的效果? 我一开始想到的...

Greenplum源码编译安装(单机及集群模式)完全攻略

公司有个项目需要安装greenplum数据库,让我这个gp小白很是受伤,在网上各种搜,结果找到的都是TMD坑货帖子,但是经过4日苦战,总算是把greenplum的安装弄了个明白,单机及集群模式都部署成功,下面由我给大家分享一下整个部署过程,并小分析一下安装过程中遇到的各种坑。 首先,说一下我的环境,CentOS 7.2.1511,64位操作系统,全新安装,...

实验1:SDN拓扑实践

实验1:SDN拓扑实践 一、实验目的 能够使用源码安装Mininet; 能够使用Mininet的可视化工具生成拓扑; 能够使用Mininet的命令行生成特定拓扑; 能够使用Mininet交互界面管理SDN拓扑; 能够使用Python脚本构建SDN拓扑。 二、实验环境 下载虚拟机软件Oracle VisualBox 或 VMware; 在虚拟机中安装U...

安装arm-linux-gcc编译器时出现错误,请大神看看怎么回事

echo '/opt/buildroot-2011.05/output/toolchain/gcc-4.3.5/gcc/ada/decl.c' >> tmp-gi.listecho '/opt/buildroot-2011.05/output/toolchain/gcc-4.3.5/gcc/ada/trans.c' >> tmp-g...

python 多进程

1.进程的创建 frommultiprocessing import Process import time,os def Hi(name): time.sleep(3) print("Hello %s" %name,time.ctime()) print("进程号是 ",os.getpid()) if __name__=="__...

curl使用

curl -H "Content-Type:application/json" -X POST --data '{"name":"zhangsan"}' http://127.0.0.1:9000/helloWorld curl命令用法: curl [options...] <url> 常用参数有: --connect-timeout <...