shell和python之間的參數傳遞

 

    咱們在使用shell調用其餘語言的程序的時候,但願可以便捷的從shell中輸入參數,而後由目標程序接收參數並運行,這樣就省去了每次須要在原程序進行修改帶來的麻煩,這裏介紹一下如何從shell中向Python傳遞參數。

     0. shell 參數的自身調用

    shell參數的自身調用是經過'$'運算符實現的,好比,有以下腳本,腳本的名字爲:run.sh:
    ###
     echo $0 $1 $2
    ###
    運行命令爲:sh run.sh abc 123
    則會輸出:run.sh  abc 123
    由此能夠看出sh命令後面的腳本名字爲第一個參數($0),日後的參數爲第二個和第三個($1,$2)

     1.shell和Python之間的參數傳遞

    shell和Python之間的參數傳遞用的是argparse模塊,程序以下:(程序的名字爲test.py)
    ###
     import  argparse

    parser = argparse.ArgumentParser()
    parser.add_argument("-id", "--input_dims",type=int,help="the dims of input")
    parser.add_argument("-pl", "--pre_lr", type=float,help="the learning rate of pretrain")
    parser.add_argument("-pe", "--pre_epochs", type=int,help="the epochs of pretrain")   
    parser.add_argument("-fl", "--fine_lr", type=float,help="the learning rate of finetune")   
    parser.add_argument("-fe", "--fine_epochs", type=int,help="the epochs of finetune")
    parser.add_argument("-bs", "--batch_size", type=int,default=36,help="batch_size ")
    parser.add_argument("-hls",'--hid_layer_size',type=int,nargs='+',help='network depth and size')
    parser.add_argument("-an", "--attname",type=str,help="the name of features")     
    parser.add_argument("-dt", "--data_type",type=str,help="the type of data")         
   
    args = parser.parse_args()
    print args

    input_dims        = args.input_dims
    pre_lr                 = args.pre_lr
    pre_epochs       = args.pre_epochs
    fine_lr                = args.fine_lr
    finetune_epochs   = args.fine_epochs
    bs                      = args.batch_size
    attName           = args.attname+"/"
    hid_layers_size = args.hid_layer_size
    dataType          = args.data_type+'/'

    ###

    shell的調用腳本以下:
    ###
     inputDims=54
    preLr=0.001
    preEpochs=3
    fineLr=0.1
    fineEpochs=3
    batchSize=36
    hls1=60
    hls2=80
    hls3=60
    attName='b_w_r_db_dw_dr'

    dataType='9box_max'
    #dataType='9box_max_over'
    #dataType='9box_max_smote'
    #dataType='1box_20'

    THEANO_FLAGS=mode=FAST_RUN,device=gpu,floatX=float32 python '/media/ntfs-1/test.py' -id $inputDims -pl $preLr -pe $preEpochs -fl $fineLr -fe $fineEpochs -bs $batchSize -hls $hls1 $hls2 $hls3 -an $attName -dt $dataType

    ###

    說明:

    1. 在parser.add_argument("-id", "--input_dims",type=int,help="the dims of input")」中,第一個參數「-id」,是在shell要輸入的指定參數;第二個參數「--input_dims」是在Python程序中要使用的變量,「type=int」是參數的類型,help是參數的幫助信息。
    2.
命令:parser.add_argument("-hls",'--hid_layer_size',type=int,nargs='+',help='network depth and size')中,「nargs='+'」意思指的是參數能夠爲多個,從shell中" -hls $hls1 $hls2 $hls3"能夠看到有3個參數,這三個參數都賦給了Python中的hid_layers_size變量,hid_layers_size 的類型爲list
    3.shell中定義變量的時候變量名,等號,變量的值之間不能有空格,不然會失敗。
相關文章
相關標籤/搜索