51Testing软件测试论坛

 找回密码
 (注-册)加入51Testing

QQ登录

只需一步,快速开始

微信登录,快人一步

查看: 2050|回复: 1

Python生成pyc文件

[复制链接]
  • TA的每日心情
    无聊
    7 小时前
  • 签到天数: 396 天

    连续签到: 2 天

    [LV.9]测试副司令

    发表于 2018-12-17 15:53:15 | 显示全部楼层 |阅读模式
    本帖最后由 测试积点老人 于 2018-12-17 15:54 编辑

    Python生成pyc文件

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


    为什么要手动提前生成pyc文件呢,主要是不想把源代码暴露出来。

    生成单个pyc文件

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

    1. python -m foo.py
    复制代码

    另外一种方式是通过代码来生成pyc文件。


    1. import py_compile
    2. py_compile.compile('/path/to/foo.py')
    复制代码
    批量生成pyc文件

    针对一个目录下所有的py文件进行编译。python提供了一个模块叫compileall,具体请看下面代码:

    1. import compileall
    2. compileall.compile_dir(r'/path')
    复制代码

    这个函数的格式如下:

    1. compile_dir(dir[, maxlevels[, ddir[, force[, rx[, quiet]]]]])
    复制代码

    参数含义:

    • maxlevels: 递归编译的层数
    • ddir: If ddir is given, it is prepended to the path to each file being compiled for use in compilation time tracebacks, and is also compiled in to the byte-code file, where it will be used in tracebacks and other messages in cases where the source file does not exist at the time the byte-code file is executed. (谁能翻译一下( ⊙o⊙?)不懂)
    • force: 如果True,不论是是否有pyc,都重新编译
    • rx: 一个正则表达式,排除掉不想要的目录
    • quiet:如果为True,则编译不会在标准输出中打印信息

    命令行为:

    1. python -m compileall <dir>
    复制代码



    回复

    使用道具 举报

    本版积分规则

    关闭

    站长推荐上一条 /1 下一条

    小黑屋|手机版|Archiver|51Testing软件测试网 ( 沪ICP备05003035号 关于我们

    GMT+8, 2024-4-16 17:00 , Processed in 0.068021 second(s), 23 queries .

    Powered by Discuz! X3.2

    © 2001-2024 Comsenz Inc.

    快速回复 返回顶部 返回列表