Python optparse模块的简单使用

optparse模块主要用来为脚本传递命令参数,采用预先定义好的选项来解析命令行参数。

示例:

import optparse

opt = optparse.OptionParser()
opt.add_option("-s", "--server", dest="server",type='string',help='target host')  # 添加一个命令行参数
opt.add_option("-P", "--port", dest="port",type='string',help='target ports',default="23")  # 添加第二个命令行参数
options, args = opt.parse_args()  # 接收命令行参数
print(options)  # option 参数,即add_option添加的

print(args)  # 非option 参数,即没有使用add_option添加

# 命令行执行的命令
python test.py -s 127.0.0.1 --port 23 xxx ooo    

执行结果

(venv) D:pythonFTP>python test.py -s 127.0.0.1 --port 23  xxx ooo
{'server': '127.0.0.1', 'port': '23'}
['xxx', 'ooo']

各个参数的含义:

dest:用于保存输入的临时变量,其值通过options的属性进行访问,存储的内容是dest之前输入的参数,多个参数用逗号分隔
type: 用于检查命令行参数传入的参数的数据类型是否符合要求,有 string,int,float 等类型
help:用于生成帮助信息
default: 给dest的默认值,如果用户没有在命令行参数给dest分配值,则使用默认值

  

  

"一劳永逸" 的话,有是有的,而 "一劳永逸" 的事却极少
原文地址:https://www.cnblogs.com/panwenbin-logs/p/14751691.html