Python: 制作精简的Python绿色发行包

#coding=gbk
#
#最小Python3.2环境, 可以在miniPython目录下,直接运行python.exe(或pythonw.exe)。
#
#前提:
#    需要安装vcredist_x86.exe包
#
#制作原理:
#    1. 把PythonXXX目录完整拷贝到制作目录,修改原有的PythonXXX目录为其它名称,使Python不直接使用。
#    2. 删除制作目录及子目录里的pyc,pyo文件
#    3. 运行制作目录下的python,然后退出
#    4. 根据重新生成的pyc文件找到需要的py文件到对应目录
#    5. 从而得到了最小的python运行环境
#
#示例:
#    1. 把Python32目录下的文件拷贝到C:\temp\Python32
#    2. 删除C:\temp\Python32目录及其子目录下的所有pyc,pyo文件
#    3. 在控制台下运行: 
#        C:\temp\Python32\python.exe E:\2012\Setup\findMinPython.py
#    4. 上面的命令会将需要的py文件拷贝到E:\2012\Setup\miniPython目录下
#    5. 将python.exe, pythonw.exe, python32.dll拷贝到E:\2012\Setup\miniPython目录下
#    精简的Python32使用环境就找出来了, 
#

# 导入基础模块
import os
import shutil

def visitDirFile(dir, visitor):
    '''递归访问目录及其子目录下的文件'''
    assert(os.path.isdir(dir)), dir
    for i in os.listdir(dir):
        fullPathName = os.path.join(dir, i)
        if os.path.isfile(fullPathName):
            if visitor(fullPathName):
                return True
        elif os.path.isdir(fullPathName):
            # 访问子目录
            if visitDirFile(fullPathName, visitor):
                return True

def findPyFile(file):
    '''查找相应的Py文件(不考虑pyo文件)'''
    if file[-4:] == '.pyc':
        # 得到编译文件对应的源文件
        dir = os.path.dirname(file)
        if dir.endswith('__pycache__'):
            dir = dir[:-11]
        # 文件中可能有点存在,要排除3.2之后的缓存
        name, ext = os.path.splitext(os.path.basename(file))
        name2, ext = os.path.splitext(name)
        if ext.startswith('.cpython'):
            name = name2
        srcFile = os.path.join(dir, '%s.py' % name)
        # 源文件可能是pyw文件
        if not os.path.isfile(srcFile):
            srcFile += 'w'
        destFile = srcFile.replace(srcDir, destDir)
        print(srcFile)
        # 保证目标目录存在
        dir = os.path.dirname(destFile)
        if not os.path.isdir(dir):
            os.makedirs(dir)
        # 拷贝文件及状态
        shutil.copy2(srcFile, destFile)

if __name__ == '__main__':
    import sys
    srcDir = os.path.dirname(sys.executable)
    destDir = os.path.join(os.path.dirname(__file__), 'miniPython')
    visitDirFile(srcDir, findPyFile)
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值