閱讀原文python
Python解析命令行讀取參數有兩種方式:sys.argv和argparseui
若是腳本很簡單或臨時使用,沒有多個複雜的參數選項,能夠直接利用sys.argv將腳本後的參數依次讀取(讀進來的默認是字符串格式)。this
import sys print("輸入的參數爲:%s" % sys.argv[1])
命令行執行效果:spa
>python demo.py 1 輸入的參數爲:1
若是參數不少,比較複雜,而且類型不統一,那麼argparse能夠很好的解決這些問題,下面一個實例解釋了argparse的基本使用方法。命令行
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)
命令行執行效果:code
>python demo.py --num_epochs 10 --num_layers 10 Namespace(num_epochs=10, num_layers=10, toy=False) False 10 10
parser.add_argument('--toy','-t',action='store_true',help='Use only 50K samples of data')
--toy:爲參數名稱;ip
-t:爲參數別稱; action='store_true':參數是否使用,若是使用則爲True,不然爲False。字符串
>python demo.py -t --num_epochs 10 --num_layers 10 Namespace(num_epochs=10, num_layers=10, toy=True) True 10 10 # 對比和上次執行的區別
help:參數說明get
實例1it
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.
轉載:寬客在線