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中定义变量的时候变量名,等号,变量的值之间不能有空格,否则会失败。

猜你喜欢

转载自www.cnblogs.com/feiniao-carrie/p/9638837.html