Python 中argparse模塊的使用

閱讀原文python

Python解析命令行讀取參數有兩種方式:sys.argv和argparsebash


一、sys.argv

若是腳本很簡單或臨時使用,沒有多個複雜的參數選項,能夠直接利用sys.argv將腳本後的參數依次讀取(讀進來的默認是字符串格式)。ui

import sys
print("輸入的參數爲:%s" % sys.argv[1])
複製代碼

命令行執行效果:this

>python demo.py 1
輸入的參數爲:1
複製代碼

二、argparse

若是參數不少,比較複雜,而且類型不統一,那麼argparse能夠很好的解決這些問題,下面一個實例解釋了argparse的基本使用方法。spa

import argparse
# description參數能夠用於描述腳本的參數做用,默認爲空
parser=argparse.ArgumentParser(description="A description of what the program does")
parser.add_argument('--toy','-t',action='store_true',help='Use only 50K samples of data')
  parser.add_argument('--num_epochs',choices=[5,10,20],default=5,type=int,help='Number of epochs.')
 parser.add_argument("--num_layers", type=int, required=True, help="Network depth.")

args=parser.parse_args()
 print(args)
print(args.toy,args.num_epochs,args.num_layers)
複製代碼

命令行執行效果:命令行

>python demo.py --num_epochs 10 --num_layers 10
Namespace(num_epochs=10, num_layers=10, toy=False)
False 10 10
複製代碼

2.1.基本使用

parser.add_argument('--toy','-t',action='store_true',help='Use only 50K samples of data')
複製代碼

--toy:爲參數名稱;code

-t:爲參數別稱; action='store_true':參數是否使用,若是使用則爲True,不然爲False。ip

>python demo.py -t --num_epochs 10 --num_layers 10
Namespace(num_epochs=10, num_layers=10, toy=True)
True 10 10 # 對比和上次執行的區別
複製代碼

help:參數說明字符串


2.2.相關參數

實例1get

parser.add_argument('--num_epochs',choices=[5,10,20],default=5,type=int,help='Number of epochs.')
複製代碼

choices:候選值,輸出參數必須在候選值裏面,否如會出現下面的結果:

>python demo.py -t --num_epochs 30 --num_layers 10
usage: demo.py [-h] [--toy] [--num_epochs {5,10,20}] --num_layers NUM_LAYERS
demo.py: error: argument --num_epochs: invalid choice: 30 (choose from 5, 10, 20)
複製代碼

default:默認值,若是不輸入參數,則使用該默認值

>python demo.py -t  --num_layers 10
Namespace(num_epochs=5, num_layers=10, toy=True)
True 5 10
複製代碼

int:參數類型

實例2

parser.add_argument("--num_layers", type=int, required=True, help="Network depth.")
複製代碼

required:爲必選參數,若是不輸入,則出現如下錯誤:

>python demo.py -t --num_epochs 10
usage: demo.py [-h] [--toy] [--num_epochs {5,10,20}] --num_layers NUM_LAYERS
demo.py: error: the following arguments are required: --num_layers
複製代碼

實例3 -h:輸出參數使用說明信息

>python demo.py -h
usage: demo.py [-h] [--toy] [--num_epochs {5,10,20}] --num_layers NUM_LAYERS
 
A description of what the program does
 
optional arguments:
-h, --help            show this help message and exit
--toy, -t             Use only 50K samples of data
--num_epochs {5,10,20}
               Number of epochs.
--num_layers NUM_LAYERS
                Network depth.
複製代碼

轉載:寬客在線

相關文章
相關標籤/搜索