[Python] Argparse module
he recommended command-line parsing module in the Python standard library
1. Basic
1 2 3 4 | import argparse parser = argparse.ArgumentParser() parser.parse_args() |
1 2 3 4 5 | $ python prog.py - - help usage: prog.py [ - h] optional arguments: - h, - - help show this help message and exit |
display the usefulness of the argparse module
2. positional argument
eg
1 2 3 4 5 | import argparse parser = argparse.ArgumentParser() parser.add_argument( "echo" ) args = parser.parse_args() print args.echo |
result
1 2 3 4 5 6 7 8 9 10 11 12 13 | $ python prog.py usage: prog.py [ - h] echo prog.py: error: the following arguments are required: echo $ python prog.py - - help usage: prog.py [ - h] echo positional arguments: echo optional arguments: - h, - - help show this help message and exit $ python prog.py foo foo |
If we want to change the argument into an integer, we can:
1 2 3 4 5 6 | import argparse parser = argparse.ArgumentParser() parser.add_argument( "square" , help = "display a square of a given number" , type = int ) args = parser.parse_args() print args.square * * 2 |
3. optional argument
1 2 3 4 5 6 | import argparse parser = argparse.ArgumentParser() parser.add_argument( "--verbosity" , help = "increase output verbosity" ) args = parser.parse_args() if args.verbosity: print "verbosity turned on" |
output
1 2 3 4 5 6 7 8 9 10 11 12 13 | $ python prog.py - - verbosity 1 verbosity turned on $ python prog.py $ python prog.py - - help usage: prog.py [ - h] [ - - verbosity VERBOSITY] optional arguments: - h, - - help show this help message and exit - - verbosity VERBOSITY increase output verbosity $ python prog.py - - verbosity usage: prog.py [ - h] [ - - verbosity VERBOSITY] prog.py: error: argument - - verbosity: expected one argument |
4. short option
1 2 3 4 5 6 7 | import argparse parser = argparse.ArgumentParser() parser.add_argument( "-v" , "--verbose" , help = "increase output verbosity" , action = "store_true" ) args = parser.parse_args() if args.verbose: print "verbosity turned on" |
output
1 2 3 4 5 6 7 8 | $ python prog.py - v verbosity turned on $ python prog.py - - help usage: prog.py [ - h] [ - v] optional arguments: - h, - - help show this help message and exit - v, - - verbose increase output verbosity |
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 智能桌面机器人:用.NET IoT库控制舵机并多方法播放表情
· Linux glibc自带哈希表的用例及性能测试
· 深入理解 Mybatis 分库分表执行原理
· 如何打造一个高并发系统?
· .NET Core GC压缩(compact_phase)底层原理浅谈
· 新年开篇:在本地部署DeepSeek大模型实现联网增强的AI应用
· DeepSeek火爆全网,官网宕机?本地部署一个随便玩「LLM探索」
· Janus Pro:DeepSeek 开源革新,多模态 AI 的未来
· 上周热点回顾(1.20-1.26)
· 【译】.NET 升级助手现在支持升级到集中式包管理