|
| 1 | +## py_compile |
| 2 | + |
| 3 | +将 py 文件编译为 pyc 文件,在前两年还说是别人都无法反编译出源文件,但是现在连[在线反编译网站](https://tool.lu/pyc/)都有了。 |
| 4 | + |
| 5 | +源代码保护还是需要再想想别的法子. |
| 6 | + |
| 7 | +py_compile 是 python 自带的官方库,在单个 python 文件中边解释边运行,在 python 类库里引用运行的时候就会自动编译出 pyc 文件。 |
| 8 | + |
| 9 | +pyc 文件是跨平台,区分版本的。在 python 虚拟机中运行,和 Java 类似。 |
| 10 | + |
| 11 | +### 使用 |
| 12 | + |
| 13 | +``` |
| 14 | +# coding=utf-8 |
| 15 | + |
| 16 | +import py_compile |
| 17 | + |
| 18 | +py_compile.compile("test.py") |
| 19 | + |
| 20 | +``` |
| 21 | + |
| 22 | +或者 在命令行中执行 |
| 23 | + |
| 24 | +``` |
| 25 | +$ python -m py_compile test.py |
| 26 | +``` |
| 27 | + |
| 28 | +### 高级用法 |
| 29 | + |
| 30 | +编译整个文件夹,使用 `compileall` 库 |
| 31 | + |
| 32 | +``` |
| 33 | +# coding=utf-8 |
| 34 | + |
| 35 | +import compileall |
| 36 | + |
| 37 | +# 编译单个文件 |
| 38 | +print compileall.compile_file("test.py") |
| 39 | + |
| 40 | +# 编译整个文件夹 |
| 41 | +print compileall.compile_dir("home") |
| 42 | + |
| 43 | +``` |
| 44 | + |
| 45 | +1. 使用 `compileall.compile_dir` 实际上也是将文件夹中的源代码单个调用 `compileall.compile_file` 方法 |
| 46 | +2. 使用 `compileall.compile_file` 实际上也是调用 `py_compile.compile` 方法 |
| 47 | +3. 编译完成后的 pyc 文件在源目录下 |
| 48 | +4. 调用成功后会返回 `1` |
| 49 | + |
| 50 | +``` |
| 51 | +$ python compileall_demo.py |
| 52 | +Compiling test.py ... |
| 53 | +1 |
| 54 | +Listing home ... |
| 55 | +Compiling home/__init__.py ... |
| 56 | +Compiling home/index.py ... |
| 57 | +1 |
| 58 | +``` |
0 commit comments