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中定義變量的時候變量名,等號,變量的值之間不能有空格,否則會失敗。


免責聲明!

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



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