1 前言
1.1 参考资料
[1] argparse基本用法, https://blog.csdn.net/yy_diego/article/details/82851661
[2] argparse简要用法总结, http://vra.github.io/2017/12/02/argparse-usage/
1.2 博客内容
最近在看Python代码的时候看到了别人使用
import argparse
这个内置的argparse包。百度了一下,作用为利用命令行向程序传入参数:就是说比如我们的某个程序有一些参数,往常我都是在程序里改,然后运行程序。而使用argparse可以在命令行下向程序传入参数。本篇博客记录一下argparse的用法。
2 正文
自己模仿参考资料写了一个小demo:
import argparse
def main():
parser = argparse.ArgumentParser("Demo of argparse")
parser.add_argument('--epochs', type=int, default=50, help="number of epochs")
parser.add_argument('--lr', type=float, default=0.01, help='learn rate')
parser.add_argument('--weights_path', type=str,
default="weights/yolo.weights", help="path to weights file")
args = parser.parse_args()
print(args)
epochs = args.epochs
lr = args.lr
weights_path = args.weights_path
print("Your model's path of weights is {}".format(weights_path))
print("The number of epoch is", epochs, "and learning rate =", lr)
if __name__ == '__main__':
main()
直接在终端运行的结果(使用默认default参数)
python test.py
输出结果:
Namespace(epochs=50, lr=0.01, weights_path=‘weights/yolo.weights’)
Your model’s path of weights is weights/yolo.weights
The number of epoch is 50 and learning rate = 0.01
查看帮助:
python test.py -h
输出结果就不放了,会显示parser.add_argument中对于每个参数的help内容和parser = argparse.ArgumentParser()中的内容。
也可以更改部分默认参数,终端输入以下内容得到更改部分参数的结果:
python test.py --epochs 200 --lr 0.5
输出结果:
Namespace(epochs=200, lr=0.5, weights_path=‘weights/yolo.weights’)
Your model’s path of weights is weights/yolo.weights
The number of epoch is 200 and learning rate = 0.5
3 结语
如有错误,欢迎各位大佬进行指正!