Python optparse模块的简单使用

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

示例:

1
2
3
4
5
6
7
8
9
10
11
12
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(optinos.server) #取值,options实际上已经被封装为类,不是字典
print(args)  # 非option 参数,即没有使用add_option添加
 
# 命令行执行的命令
python test.py -s 127.0.0.1 --port 23 xxx ooo    

执行结果

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

各个参数的含义:

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

  

  

 

posted @   百衲本  阅读(249)  评论(0编辑  收藏  举报
编辑推荐:
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· AI 智能体引爆开源社区「GitHub 热点速览」
· Manus的开源复刻OpenManus初探
· 写一个简单的SQL生成工具
cnblogs_post_body { color: black; font: 0.875em/1.5em "微软雅黑" , "PTSans" , "Arial" ,sans-serif; font-size: 15px; } cnblogs_post_body h1 { text-align:center; background: #333366; border-radius: 6px 6px 6px 6px; box-shadow: 0 0 0 1px #5F5A4B, 1px 1px 6px 1px rgba(10, 10, 0, 0.5); color: #FFFFFF; font-family: "微软雅黑" , "宋体" , "黑体" ,Arial; font-size: 23px; font-weight: bold; height: 25px; line-height: 25px; margin: 18px 0 !important; padding: 8px 0 5px 5px; text-shadow: 2px 2px 3px #222222; } cnblogs_post_body h2 { text-align:center; background: #006699; border-radius: 6px 6px 6px 6px; box-shadow: 0 0 0 1px #5F5A4B, 1px 1px 6px 1px rgba(10, 10, 0, 0.5); color: #FFFFFF; font-family: "微软雅黑" , "宋体" , "黑体" ,Arial; font-size: 20px; font-weight: bold; height: 25px; line-height: 25px; margin: 18px 0 !important; padding: 8px 0 5px 5px; text-shadow: 2px 2px 3px #222222; } cnblogs_post_body h3 { background: #2B6695; border-radius: 6px 6px 6px 6px; box-shadow: 0 0 0 1px #5F5A4B, 1px 1px 6px 1px rgba(10, 10, 0, 0.5); color: #FFFFFF; font-family: "微软雅黑" , "宋体" , "黑体" ,Arial; font-size: 18px; font-weight: bold; height: 25px; line-height: 25px; margin: 18px 0 !important; padding: 8px 0 5px 5px; text-shadow: 2px 2px 3px #222222; } 回到顶部 博客侧边栏 回到顶部 页首代码 回到顶部 页脚代码
点击右上角即可分享
微信分享提示