python标准库介绍——26 getopt 模块详解
==getopt 模块== ``getopt`` 模块包含用于抽出命令行选项和参数的函数, 它可以处理多种格式的选项. 如 [Example 2-23 #eg-2-23] 所示. 其中第 2 个参数指定了允许的可缩写的选项. 选项名后的冒号(:) 意味这这个选项必须有额外的参数. ====Example 2-23. 使用 getopt 模块====[eg-2-23] ``` File: getopt-example-1.py import getopt import sys # simulate command-line invocation # 模仿命令行参数 sys.argv = ["myscript.py", "-l", "-d", "directory", "filename"] # process options # 处理选项 opts, args = getopt.getopt(sys.argv[1:], "ld:") long = 0 directory = None for o, v in opts: if o == "-l": long = 1 elif o == "-d": directory = v print "long", "=", long print "directory", "=", directory print "arguments", "=", args *B*long = 1 directory = directory arguments = ['filename']*b* ``` 为了让 ``getopt`` 查找长的选项, 如 [Example 2-24 #eg-2-24] 所示, 传递一个描述选项的列表做为第 3 个参数. 如果一个选项名称以等号(=) 结尾, 那么它必须有一个附加参数. ====Example 2-24. 使用 getopt 模块处理长选项====[eg-2-24] ``` File: getopt-example-2.py import getopt import sys # simulate command-line invocation # 模仿命令行参数 sys.argv = ["myscript.py", "--echo", "--printer", "lp01", "message"] opts, args = getopt.getopt(sys.argv[1:], "ep:", ["echo", "printer="]) # process options # 处理选项 echo = 0 printer = None for o, v in opts: if o in ("-e", "--echo"): echo = 1 elif o in ("-p", "--printer"): printer = v print "echo", "=", echo print "printer", "=", printer print "arguments", "=", args *B*echo = 1 printer = lp01 arguments = ['message']*b* ``` ``` [!Feather 注: 我不知道大家明白没, 可以自己试下: myscript.py -e -p lp01 message myscript.py --echo --printer=lp01 message ] ```
如果觉得对您有帮助,麻烦您点一下推荐,谢谢!
好记忆不如烂笔头
好记忆不如烂笔头
分类:
python
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术