【python】argparse 模塊,執行腳本時獲取命令行參數 command line arguments


執行測試腳本時需要通過命令行指定測試報告的名稱

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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM