Python-AMF3-序列化-打包配置些文件

代码

这个是以前写的,记录一下, 应该用的是:python 2.7.5版本的

测试工程,里面的:cfg_pack_global.py就是下面的代码了

#coding=utf-8
__author__ = 'jave.lin'
"""
    autor:jave.lin
    date:2016-08-13 16:19
"""

import zlib
import re
import sys
import getopt
import os
import time
import json
import codecs
import pip
import imp

def getModule(moduleName, autoInstallAndLoad = True):
    try:
        return __import__(moduleName)
    except:
        if autoInstallAndLoad:
            print 'start install module:' + moduleName
            pip.main(['install'], moduleName)

            f, fname, desc = imp.find_module(moduleName)
            print 'start load module:' + moduleName
            return imp.load_module(moduleName, f, fname, desc)
        else:
            return None

pyamf = getModule('pyamf')
if pyamf == None:
    print 'Unabled found the module: pyamf'
    sys.exit()

global inputPath
global outputPath
global absolutePath
global showInfo
global startTime;
global includeP
global fetchFnP
#fetchOutputDirP = re.compile(r'(.*)[\\|/]\w+.cfg$')
global fetchLastDirNameP
global checkPathLastCharP
global rootObj

def showUsage(reason):
    print "reason:" + reason
    print """usage:
        -i value or --inputPath=value           [Required] The path which to pack
        -o value or --outputPath=value          [Required] The path which to output
        -a or --absolutePath                    [Optional] Decide the 'inputPath/outputPath' args how to use, Default(not set): Relatived
        -h or --help                            [Optional] Show usage, if set this arg, will exit after show usage
        --showInfo                              [Optional] Show the help info"""

def getoptsHandle():
    global inputPath
    global outputPath
    global absolutePath
    global showInfo
    try:
        options, args = getopt.getopt(sys.argv[1:], "ahi:o:", ["absolutPath", "help", "inputPath=", "outputPath=", "showInfo"])
    except getopt.GetoptError:
        showUsage("getopt.GetoptError")
        sys.exit()

    for name, value in options:
        if name in ("-h", "--help"):
            showUsage("help info");
            sys.exit()
        if name in ("-i", "--inputPath"):
            inputPath = value
        if name in ("-o", "--outputPath"):
            outputPath = value
        if name in ("-a", "--absolutePath"):
            absolutePath = True
        if name in ("--showInfo"):
            showInfo = True

    if inputPath == None or outputPath == None:
        showUsage("inputPath == None or outputPath == None")
        sys.exit()

    if absolutePath == False:
        inputPath = sys.path[0] + "\\" + inputPath
        outputPath = sys.path[0] + "\\" + outputPath

    if os.path.exists(inputPath) == False:
        print "path:" + inputPath + ", is not existed!"
        sys.exit()

def exportHandle(arg_path, parentName):
    global outputPath
    global includeP
    global fetchFnP
    global checkPathLastCharP
    global rootObj

    fileArr = os.listdir(arg_path)
    for fn in fileArr:
        fullN = arg_path + "/" + fn
        if os.path.isdir(fullN):
            exportHandle(arg_path + "/" + fn, parentName + "_" + fn)
        else:
            if includeP.search(fn):
                with codecs.open(fullN, "r", "utf-8") as f:
                    m = fetchFnP.search(fn)
                    pureFn = m.groups(0)[0]
                    obj = json.loads(f.read())
                    rootObj[pureFn] = obj
            else:
                if showInfo:
                    print "not json file:" + fn
    print 'p:' + arg_path + ', f:' + parentName, 

    compress = zlib.compressobj(9)

    encoder = pyamf.get_encoder(pyamf.AMF3)
    stream = encoder.stream
    encoder.writeElement(rootObj)
    amf_data = stream.getvalue()
    amf_data_size = len(amf_data)

    if showInfo:
        print "src size: %d bytes" % amf_data_size,

    opPath = outputPath;
    if checkPathLastCharP.search(outputPath) == None:
        opPath += "/"
    opPath += parentName + ".cfg"
    with open(opPath, "wb") as output_file:
        output_file.write(compress.compress(amf_data))
        output_file.write(compress.flush())
        if showInfo:
            print "compressed size: %d bytes" % output_file.tell()

def main():
    global absolutePath
    global showInfo
    global includeP
    global fetchFnP
    global fetchLastDirNameP
    global checkPathLastCharP
    global rootObj
    global startTime
    global showInfo

    absolutePath = False
    showInfo = False
    includeP = re.compile(r'.json$')
    fetchFnP = re.compile(r'[\\|/]*(\w+).json$')
    fetchLastDirNameP = re.compile(r'[\\|/](\w+)$')
    checkPathLastCharP = re.compile(r'[\\|/]$')
    rootObj = {};

    getoptsHandle()

    startTime = time.time();

    dName = fetchLastDirNameP.search(inputPath).groups(0)[0]
    exportHandle(inputPath, dName)

    if showInfo:
        print "start..."

    if showInfo:
        print "use time: %.2f s" % (time.time() - startTime);

    if showInfo:
        print "end"

if __name__ == '__main__':
    main()
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值