argparse模塊主要用來爲腳本傳遞命令參數功能,使他們更加靈活。函數
代碼:ui
1 parser = argparse.ArgumentParser() #創建解析器,必須寫
調用add_argument()向ArgumentParser對象添加命令行參數信息,這些信息告訴ArgumentParser對象如何處理命令行參數。能夠經過調用parse_agrs()來使用這些命令行參數。spa
參數:命令行
name or flags…[, action][, nargs][, const][, default][, type][, choices][, required][, help][, metavar][, dest] code
name or flags:是必須的參數,該參數接受選項參數或者是位置參數(一串文件名)
default: 當參數須要默認值時,由這個參數指定,對象
type: 使用這個參數,轉換輸入參數的具體類型,這個參數能夠關聯到某個自定義的處理函數,這種函數一般用來檢查值的範圍,以及合法性blog
choices: 這個參數用來檢查輸入參數的範圍io
required: 當某個選項指定須要在命令中出現的時候用這個參數class
help: 使用這個參數描述選項做用test
1 parser = argparse.ArgumentParser() 2 parser.add_argument('--gan_type', type=str, default='GAN', 3 choices=['GAN', 'CGAN', 'infoGAN', 'ACGAN', 'EBGAN', 'BEGAN', 'WGAN', 'WGAN_GP', 'DRAGAN', 'LSGAN', 'VAE', 'CVAE'], 4 help='The type of GAN', required=True) 5 parser.add_argument('--dataset', type=str, default='mnist', choices=['mnist', 'fashion-mnist', 'celebA'], 6 help='The name of dataset') 7 parser.add_argument('--epoch', type=int, default=20, help='The number of epochs to run') 8 parser.add_argument('--batch_size', type=int, default=64, help='The size of batch') 9 parser.add_argument('--z_dim', type=int, default=62, help='Dimension of noise vector')
經過調用parse_args()來解析ArgumentParser對象中保存的命令行參數:將命令行參數解析成相應的數據類型並採起相應的動做,它返回一個Namespace
對象。
1 print(parser.parse_args())
輸出: usage: test.py [-h] --gan_type
{GAN,CGAN,infoGAN,ACGAN,EBGAN,BEGAN,WGAN,WGAN_GP,DRAGAN,LSGAN,VAE,CVAE}
[--dataset {mnist,fashion-mnist,celebA}] [--epoch EPOCH]
[--batch_size BATCH_SIZE] [--z_dim Z_DIM]
test.py: error: the following arguments are required: --gan_type 由於 required
這樣寫的話:
1 print(parser.parse_args(["--gan_type", "GAN"])) #傳入參數
輸出: Namespace(batch_size=64, dataset='mnist', epoch=20, gan_type='GAN', z_dim=62)
從對象中直接拿參數:
a = parser.parse_args(["--gan_type", "GAN"]
print(a.z_dim, a.batch_size)結果:62 64