Ubuntu 18.04终端下使用argparse为Python3应用传参异常问题咨询
核心错误原因
你给所有add_argument配置项的dest参数都设成了同一个值main。argparse解析参数时,会按照传入顺序把后面的值持续覆盖前面对应这个main属性的内容,最终只会留下最后传入的-n_iter 100的值,这就是你看到输出始终是Namespace(main='100')的原因。
修正方法
- 移除所有重复的
dest="main"配置:argparse默认会自动根据长选项参数(如--annotation_file)生成对应的类属性名,自动把参数里的连字符替换为下划线,不需要手动指定dest。 - 给数字类型的参数补全类型声明,避免所有命令行传入的值都被解析为字符串。
修正后的可运行代码
if __name__ == "__main__": from argparse import ArgumentParser parser = ArgumentParser() parser.add_argument("-af", "--annotation_file", default=None, help="Path to annotated file") parser.add_argument("-em", "--existing_model_path", default=None, help="Retrain existing model or train from scratch") parser.add_argument("-output_dir", "--output_dir_to_save_model", default="/app/model", help="Path to save newly generated NER model") parser.add_argument("-n_iter", "--num_iter", type=int, default=100, help="Number of iterations to train the model") args = parser.parse_args() print(args) main(args)
修正后效果
执行你原本的终端命令:
python3 app/app.py -af app/annotation_file.json -em app/model/ -output_dir app/new_model/ -n_iter 100
args对象会完整保留所有传入的参数值,打印输出类似:
Namespace(annotation_file='app/annotation_file.json', existing_model_path='app/model/', output_dir_to_save_model='app/new_model/', num_iter=100)
在main()函数内,可以直接通过args.annotation_file、args.existing_model_path、args.num_iter这类属性名,读取对应的参数值。
注意:如果业务场景确实需要手动指定
dest,必须为每个参数配置唯一的属性名,禁止多个参数共用同一个dest值,否则必然会出现参数覆盖的问题。
内容的提问来源于stack exchange,提问作者SteveS
相关产品推荐
相关产品推荐

