【python】argparse 模块,执行脚本时获取命令行参数 command line arguments

时间:2022-11-09 09:45:27

执行测试脚本时需要通过命令行指定测试报告的名称

1. 使用默认的sys.argv

# coding=utf-8
import  sys

if __name__ == "__main__":
    print "arg test"
    print sys.argv

执行脚本,sys.argv返回的是脚本运行时,所有参数的list,0位为脚本名称,以后的存放为执行参数

C:\PycharmProjects\p3\src\pyproject1>python argTest.py -r report.html
arg test
['argTest.py', '-r', 'report.html']

2. 使用argparse模块,不添加任何参数

# coding=utf-8
import argparse

if __name__ == "__main__":
    print "arg test"
    parser = argparse.ArgumentParser()
    parser.parse_args()

执行脚本

C:\PycharmProjects\p3\src\pyproject1>python argTest.py
arg test

C:\PycharmProjects\p3\src\pyproject1>python argTest.py -h
arg test
usage: argTest.py [-h]

optional arguments:
  -h, --help  show this help message and exit

3. 使用argparse模块,添加参数,

# coding=utf-8
import argparse

if __name__ == "__main__":
    print "arg test"
    parser = argparse.ArgumentParser()
    parser.add_argument("reportname", help="set the reportname by this argument")
    args = parser.parse_args()
    print args.report

执行脚本:

C:\PycharmProjects\p3\src\pyproject1>python argTest.py
arg test
usage: argTest.py [-h] reportname
argTest.py: error: too few arguments

C:\PycharmProjects\p3\src\pyproject1>python argTest.py -h
arg test
usage: argTest.py [-h] reportname

positional arguments:
  reportname  set the reportname by this argument

optional arguments:
  -h, --help  show this help message and exit

C:\PycharmProjects\p3\src\pyproject1>python argTest.py report1.html
arg test report1.html

4. 再添加一个可选择的参数,没有配置可选参数时,读取该参数,获取的是None

# coding=utf-8
import argparse

if __name__ == "__main__":
    print "arg test"
    parser = argparse.ArgumentParser()
    parser.add_argument("reportname", help="set the reportname by this argument")
    parser.add_argument('--date', help="executed date")
    args = parser.parse_args()
    print args.reportname
    print args.date

执行脚本:

C:\PycharmProjects\p3\src\pyproject1>python argTest.py
arg test
usage: argTest.py [-h] [--date DATE] reportname
argTest.py: error: too few arguments

C:\PycharmProjects\p3\src\pyproject1>python argTest.py -h
arg test
usage: argTest.py [-h] [--date DATE] reportname

positional arguments:
  reportname   set the reportname by this argument

optional arguments:
  -h, --help   show this help message and exit
  --date DATE  executed date

C:\PycharmProjects\p3\src\pyproject1>python argTest.py report2.html
arg test
report2.html
None

C:\PycharmProjects\p3\src\pyproject1>python argTest.py report2.html --date 20170428
arg test
report2.html
20170428

5. 引申,argparse还可执行参数类型,等很多高级设置

使用手册参照官网https://docs.python.org/3/library/argparse.html