栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

python 批量编译pyc文件

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

python 批量编译pyc文件

        pyc文件是py文件编译后生成的字节码文件(byte code),pyc文件经过python解释器最终会生成机器码运行。因此:pyc文件是可以跨平台部署的,类似Java的.class文件,一般py文件改变后,都会重新生成pyc文件。

1、Python生成单个pyc文件

        1)对于py文件,可以执行下面命令来生成pyc文件。

python -m test.py

        2)通过python代码来生成pyc文件。

import py_compile py_compile.compile("test.py")
2、Python批量生成pyc文件

        针对一个目录下所有的py文件进行编译。python提供了一个模块叫compileall,使用命令行:python -m compileall,或代码:

import compileall 
compileall.compile_dir(r'/path')

compile_dir函数用法:compile_dir(dir[, maxlevels[, ddir[, force[, rx[, quiet]]]]]) 

compile_dir参数含义:

        maxlevels:递归编译的层数;

        ddir:如果给出了ddir,它将被预先添加到编译的每个文件的路径以用于编译时间回溯,并且还被编译到字节码文件中,在源文件中,它将用于回溯和其他消息中 文件代码文件执行时文件不存在;

        force:如果True,不论是是否有pyc,都重新编译;

        rx:一个正则表达式,排除掉不想要的目录;

        quie:如果为True,则编译不会在标准输出中打印信息。

3、工程实践
def project_compile():
    data_dir = os.path.realpath(r"E:projectapp")
    ret_dir = r"C:UsersiDesktopapp_pyc"
    exclude = [".idea", ".git"]

    compileall.compile_dir(data_dir, force=True)

    file_paths = walk_file(data_dir)
    total_cnt = len(file_paths)
    print(len(file_paths), file_paths)
    for idx, file_path in enumerate(file_paths):
        print(idx, total_cnt, file_path)
        if len([v for v in exclude if file_path.find(v) != -1]):
            print("ignoreL:", file_path)
            continue

        if file_path.endswith(".py"):
            continue

        ret_file_path = path.join(ret_dir, file_path[len(data_dir) + 1:])
        if not file_path.endswith(".pyc"):
            cp(file_path, ret_file_path)
            continue

        name = path.basename(ret_file_path)
        if ".cpython-37" in name:
            name = name.replace(".cpython-37", "")

        ret_dir_name = path.dirname(ret_file_path)
        if path.basename(ret_dir_name) == "__pycache__":
            ret_dir_name = path.dirname(ret_dir_name)
        ret_file_path = path.join(ret_dir_name, name)
        cp(file_path, ret_file_path)

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/875517.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号