本文摘自php中文网,作者不言,侵删。
本篇文章给大家带来的内容是关于Python中argparse库的基本使用(示例),有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。基本使用
1 2 3 4 5 | import argparse
# 创建解析器
parser = argparse.ArgumentParser(description = 'This is a test' )
parser.parse_args()
|
可以在shell中测试:
1 2 | $ python test.py --help
...
|
添加参数
1 2 3 4 5 6 | import argparse
parser = argparse.ArgumentParser(description = 'This is a test' )
parser.add_argument( "-p" , "--port" ,help= 'increase output port' ) # 定义了可选参数-p和--port,赋值后,其值保存在args.port中(其值都是保存在最后一个定义的参数中)
args = parser.parse_args()
print (args. echo )
|
使用时候:
1 2 3 | $ python test.py -p 50
或
$ python test.py --port 50
|
指定类型
我们也可以在添加参数的时候指定其类型。
1 2 3 4 | import argparse
parser = argparse.ArgumentParser(description = 'This is a test' )
parser.add_argument( "square" ,help= "display a given number" ,type=int) # 指定给square的参数为int类型
|
可选参数
1 2 3 4 5 6 | import argparse
parser = argparse.ArgumentParser()
parser.add_argument( "-v" , help= "increase output verbosity" )
args = parser.parse_args()
if args.v:
print ( "v turned on" )
|
使用:
以上就是Python中argparse库的基本使用(示例)的详细内容,更多文章请关注木庄网络博客!!
相关阅读 >>
Python如何输出商和余数
Python要在linux下编程吗
Python怎么区分不同数据类型
Python要安装什么软件
Python实现跨excel的工作表sheet之间的复制方法
Python为什么要用class
怎么卸载Python 3.6?
Python网络编程之使用select实现socket全双工异步通信功能
如何将字符串转换为datetime
vs可以写Python吗
更多相关阅读请进入《Python》频道 >>
人民邮电出版社
python入门书籍,非常畅销,超高好评,python官方公认好书。
转载请注明出处:木庄网络博客 » Python中argparse库的基本使用(示例)