本文摘自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 numpy怎么提取矩阵的指定行列
详细讲解 Python实现对图像进行掩膜遮罩处理
Python使用cx_oracle模块操作oracle数据库详解
怎么安装Python的pygame库文件
利用Python如何爬取js里面的内容
基于Python批量处理dat文件及科学计算的方法
Python如何转换时间戳
Python程序怎么变成软件
Python如何使用xlwt模块操作excel
更多相关阅读请进入《Python》频道 >>
人民邮电出版社
python入门书籍,非常畅销,超高好评,python官方公认好书。
转载请注明出处:木庄网络博客 » Python中argparse库的基本使用(示例)