2020年2月

import zipfile
import tools
import StringIO
import os


def zip_add_dir(handle, dirname):
    for root, dirs, fs in os.walk(dirname):
       for f in fs:
           if f.endswith(".py"):
               handle.write(os.path.join(root, f))

def pack():
    # toolname为项目名称,打包后会生成的文件
    toolname='ivrtool'
    buf_zip = StringIO.StringIO()
    buf_zip.write("#!/bin/env  python2\n")
                
    fzip= zipfile.ZipFile(buf_zip, "w")
    # 项目必须要有__main__.py,为执行入口
    fzip.write("__main__.py")
    # tools 为py源码目录,如有多个,需要都加入
    zip_add_dir(fzip, "tools")
    fzip.close()
    buf_zip.seek(0)
    handle=open(toolname, "w")
    while True:
        buf = buf_zip.read(1024)
        if not buf:
            break
        handle.write(buf)
    handle.close()
    buf_zip.close()
    print "%s pack success" % toolname

if __name__ == "__main__":
    pack()