python基础 pyc

关于pyc的几点记录:

python运行时会将python语句----->"字节码"------>转发到"虚拟机"

字节码:在大型的python程序中 为了提高运行效率  允许python进程在服务器写入字节码文件即pyc文件,这是一种启动速度的优化

下一次程序运行时,py文件没有改动,则直接加载pyc,跳过编译过程,通过检查源文件和字节码文件的时间戳,判断是否需要重新编译

如果机器不允许写入字节码文件,则在编译之后,在内存中生成,在程序执行结束之后 文件会自动丢弃

如果环境中无源文件,只有pyc字节码文件,该程序也可以执行

有别于c/c++的 build  make步骤

这里的字节码文件并不是二进制的代码  ,字节码指令在运行时并不会像cpu指令那样快

pvm python虚拟机

是一个迭代运行字节码的大循环 一个接一个的完成操作 是python的运行引擎

Python生成pyc文件的方法

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

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

生成单个pyc文件

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

python -m foo.py

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

import py_compile
py_compile.compile('/path/to/源文件名称.py')

批量生成pyc文件-----为某个目录生成pyc

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

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

这个函数的格式如下:

compile_dir(dir, maxlevels=10, ddir=None, force=False, rx=None,
quiet=0, legacy=False, optimize=-1, workers=1)

参数含义:

dir:       the directory to byte-compile
maxlevels: maximum recursion level (default 10)
ddir: the directory that will be prepended to the path to the
file as it is compiled into each byte-code file.
force: if True, force compilation, even if timestamps are up-to-date
quiet: full output with False or 0, errors only with 1,
no output with 2
legacy: if True, produce legacy pyc paths instead of PEP 3147 paths
optimize: optimization level or -1 for level of the interpreter
workers: maximum number of parallel workers

命令行为:

python -m compileall <dir>

psyco不是python的一种实现方式,是一个扩展字节码执行的模块,让程序运行更快

psyco可将部分程序的字节码转换成底层真正的二进制代码机器代码 在理想情况下 通过psyco优化的代码 可以像c一样快
import psyco
psyco.full()


另外,使用psyco.profile()可以对大程序进行适当分析,以确定哪些函数最值得编译。
psyco.log()函数用来记录profile()得到的信息,下次就可以运行就能更快一点。
psyco.bind(myfunc)指定对函数myfunc进行编译,可以做到比full()更精细的控制。
psyco.proxy(f)创建一个新的函数,它的代码是由f编译得到二进制码   测试使用较好



shedskin c++转换器
将python代码转换为c++代码,经过编译 可以得到机器代码

posted @ 2019-07-17 17:57  summer.秋  阅读(600)  评论(0编辑  收藏  举报