Intro

  argparse是 Python 标准库中推荐的命令行解析模块,花里胡哨的东西不说了。目前用的最多的时,再起python任务时,通过这个package,把相关参数通过命令行的方式传入。

  python版本信息:

import argparse
import sys

print("Python版本:",sys.version)
print("argparse版本:",argparse.__version__)
Python版本: 3.7.0 (default, Jun 28 2018, 08:04:48) [MSC v.1912 64 bit (AMD64)]
argparse版本: 1.1

Demo

import argparse
import sys
if __name__ == '__main__':
print("Python版本:", sys.version)
# print("argparse版本:", argparse.__version__)
parser = argparse.ArgumentParser()
# type指定数据类型,建议str传入,后续再代码里进行格式转换
# required为是否是必传参数,True但是不传,报错
parser.add_argument("--hdfs_path", help="hdfs address", type=str, required=True)
parser.add_argument("--hive_table", help="hive table", type=str, required=False)
# 解析参数
args = parser.parse_args()
hdfs_path = args.hdfs_path
hive_table = args.hive_table
print("hdfs_path is:%s" % hdfs_path)
print("hdfs_path is:%s" % hive_table)

在命令行执行​​python D:test.py --hdfs_path testhdfs --hive_table testhive​​​ 或者Pycharm的Parameters中填写​​--hdfs_path testhdfs --hive_table testhive​

Ref

​[1] https://docs.python.org/zh-cn/3/howto/argparse.html​

                                2020-07-08 于南京市江宁区九龙湖