What ?
.pyc格式的文件,是python中生成的一种文件类型,类似于Java的Class字节码文件,是由编译器编译得来的,供解释器使用;
最大的用途是,当我们部署程序时,不想暴露源码,可以使用pyc文件,达到保护源码的目的;
How ?
py_compile 模块
生成.pyc文件时,需要用到py_compile模块,首先导入模块,环境Pycharm+Python3.7: 在Pycharm里搜compile包,显示的没有相关的,  于是直接在Terminal里以命令行导入,pip install compile 
生成.pyc文件
import compile
py_compile.compile('C:\Users\Song\Desktop\VGG16-MNIST\VGG16.py')
 执行完后在当前文件夹下生成一个文件夹,_pycache_ 
批量生成.pyc文件
import compileall
compileall.compile_dir('C:\Users\Song\Desktop\VGG16-MNIST'')
调用.pyc文件
_pycache_文件夹的.pyc的文件名和.py不一样,在调用时,先将其拷贝到.py所在文件夹中,然后更改名字,最后直接import 
Note
- 生成的.pyc文件,必须在同样的python版本中使用,比如上面的例子VGG16.cpython-37.pyc,只能在python 3.7版本下运行
- 在调用时,有些情况会报错,对于直接from A import B 函数时,此时若文件夹下只有A.pyc,没有A.py文件,则会报错
|