vproc.py 5.09 KB
#!/usr/bin/python
# encoding:utf-8

#######################################################
#   author: liuh    2018-10-24
#   version: v1.0   
#   copy to device /usr/local/bin/vproc
#######################################################

import sys
import getopt
import os
import shutil

#######################config#####################
ROOT_PATH="/root/UserApp/vproc"
##################################################

def usage():
    print("""
    useage: vproc command [options]

    there are vproc commands:
        read    read a key's value
        write   write a key's value
        clean   remove group of items
    
    write command options:
        [+]-k any, --key=any | status item key.
        [+]-v any, --value=any | status item value.
        example:
            vproc write --key=vaserver.va0.cameraname --value=camera1
            vproc write --key=vaserver.va0.playok --value=1

    read command options:   
        [+]-k any, --key=any | status item key.
        example:
            vproc read --key=vaserver.va0.cameraname
            if executed write command example, it would be print camera1
            

    clean command options:
        [+]-p any, --path=any | the items's group key path
        example:
            vproc clean --path=vaserver.va0
            if executed write command example, the dir:VPROC_ROOT/vaserver/va0 would be remove.
            
    """)
    

def write_single_status(key, value):
    paths = key.split('.')
    paths_len = len(paths)
    if(paths_len<2):
        print("invalid key path, must be greater than 2 level")
        sys.exit(-1)
    if(paths_len>50):
        print("invalid key path, level too deep")
        sys.exit(-1)
    fullpath = ROOT_PATH
    for path in (paths[:-1]):
        fullpath = fullpath+ "/" + path
    if not os.path.exists(fullpath):
        os.makedirs(fullpath)
    fullpath = fullpath+"/"+paths[-1]

    with open(fullpath, 'w') as f:
        f.write(value)

def read_single_status(key):
    paths = key.split('.')
    paths_len = len(paths)
    if(paths_len<2):
        print("invalid key path, must be greater than 2 level")
        sys.exit(-1)
    fullpath = ROOT_PATH
    for path in paths:
        fullpath = fullpath+ "/" + path
    if not os.path.exists(fullpath):
        return ""
    str=""
    with open(fullpath, 'r') as f:
        strs=f.readlines()
        if(len(strs)>0):
            str = strs[0]
    
    return str


def remove_items(key_path):
    paths = key_path.split('.')
    paths_len = len(paths)
    if(paths_len<1):
        print("invalid key path, must be greater than 1 level")
        sys.exit(-1)
    fullpath = ROOT_PATH
    for path in paths:
        fullpath = fullpath+ "/" + path

    if(os.path.exists(fullpath)):
        if(os.path.isfile(fullpath)):
            os.remove(fullpath)
            # print("remove {}".format(fullpath))
        if(os.path.isdir(fullpath)):
            shutil.rmtree(fullpath)
            # print("rmdir {}".format(fullpath))
    else:
        print("no suck file or dir: {}".format(fullpath))
    

def main(): 
    argc = len(sys.argv)
    if argc < 3 or (sys.argv[1]!= "read" and sys.argv[1]!= "write" and sys.argv[1]!= "clean"):
        usage()
        sys.exit(-1)
    
    try:
        options,args = getopt.getopt(sys.argv[2:],"-h-k:-v:-p:",["help","key=","value=", "path="])
    except getopt.GetoptError:
        print("error: invalid args")
        sys.exit(-1)
    
    keys=[]
    values=[]
    key_path=[]
    if(sys.argv[1] == "write"):
        for name,value in options:
            if name in ("-h","--help"):
                usage()
            if name in ("-k","--key"):
                keys.append(value)
            if name in ("-v","--value"):
                values.append(value)
        keys_len = len(keys) 
        values_len = len(values) 
        if keys_len != values_len:
            print("invalid args, keys count is {}, values count is {}".format(keys_len, values_len))
            sys.exit(-1)
        for index in range(len(keys)):
            write_single_status(keys[index], values[index])
        sys.exit(0)
    if(sys.argv[1] == "read"):
        for name,value in options:
            if name in ("-h","--help"):
                usage()
            if name in ("-k","--key"):
                keys.append(value)
            if name in ("-v","--value"):
                values.append(value)
        for index in range(len(keys)):
            readvalue = read_single_status(keys[index])
            if(len(values)>0):
                if(index < len(values)-1):
                    defaultvalue = values[index]
                else:
                    defaultvalue = values[0]

            if(readvalue == "" and len(values)>0):
                print(defaultvalue)
            else:
                print(readvalue)
        sys.exit(0)
    if(sys.argv[1] == "clean"):
        for name,value in options:
            if name in ("-h","--help"):
                usage()
            if name in ("-p","--path"):
                key_path.append(value)
        for index in range(len(key_path)):
            remove_items(key_path[index])
        sys.exit(0)
        

if __name__ == '__main__':
    main()