argparse 是python自带的命令行参数解析包,可以用来方便地读取命令行参数。
它的使用也比较简单。
1.基本框架
下面是采用argparse从命令行获取用户名,该python的文件名为:fun_test.py
import argparse def main(): parser = argparse.ArgumentParser(description="Demo of argparse") parser.add_argument('-n','--name', default=' Li ') parser.add_argument('-y','--year', default='20') args = parser.parse_args() print(args) name = args.name year = args.year print('Hello {} {}'.format(name,year)) if __name__ == '__main__': main()
执行命令python fun_test.py结果如下:
在上面的代码中,我们先导入了argparse这个包,然后包中的ArgumentParser类生成一个parser对象(好多博客中把这个叫做参数解析器),其中的description描述这个参数解析器是干什么的,当我们在命令行显示帮助信息的时候会看到description描述的信息。
接着我们通过对象的add_argument函数来增加参数。这里我们增加了两个参数name和year,其中'-n','--name'表示同一个参数,default参数表示我们在运行命令时若没有提供参数,程序会将此值当做参数值。执行结果如上图所示。
最后采用对象的parse_args获取解析的参数,由上图可以看到,Namespace中有两个属性(也叫成员)这里要注意个问题,当'-'和'--'同时出现的时候,系统默认后者为参数名,前者不是,但是在命令行输入的时候没有这个区分接下来就是打印参数信息了。
当执行命令python fun_test.py -n Wang --year '26'结果如下:
当执行命令python fun_test.py -h
可以查看帮助信息
转自:https://blog.csdn.net/yy_diego/article/details/82851661