Python的文件范例引见:
.py python的源代码文件
.pyc Python源代码import后,编译生成的字节码
.pyo Python源代码编译优化生成的字节码。pyo比pyc并没有优化若干,只是去掉了断言
.pyd Python的动态链接库(Windows平台)
.py, .pyc, .pyo 运转速率险些无差别,只是pyc, pyo文件加载的速率更快,不能用文本编辑器检察内容,反编译不太轻易
本文的目的是将test.py文件生成test.c文件,然后将test.c文件作为Python源码的一部分,从新编译生成Python,运用时直接import test即可运用test模块。
Cython基础引见:
文档中如许总结Cython:
Cython is an optimising static compiler for both the Python programming language and the extended Cython programming language (based on Pyrex). It makes writing C extensions for Python as easy as Python itself.
是一个Python编程言语的编译器,写C扩大就像写Python代码一样轻易。
其最主要的功用是:
- write Python code that calls back and forth from and to C or C++ code natively at any point.
即 将Python代码翻译为C代码。以后就能够像前面文章引见的C言语扩大Python模块运用这些C代码了。
Cython基础用法:
在运用Cython编译Python代码时,务必要装置C/C++编译器,微软为Python供应了专用的编译器Microsoft Visual C++ Compiler for Python 2.7(包括32位和64位) 下载地点: http://aka.ms/vcpython27 百度云链接: https://pan.baidu.com/s/15ZfW00fXdNS9H6KGVEsnsQ 提取码: hhhy
1.下载完成并装置。以本机为例,装置完成后的途径为:
C:\Users\Administrator\AppData\Local\Programs\Common\Microsoft\Visual C++ for Python\9.0
2.修正python代码
修正python装置目次下Lib\distutils\msvc9compiler.py文件(若有必要能够msvccompiler.py文件也须要做响应变动,视体系而定),找到get_build_version要领直接return 9.0
然后再找到find_vcvarsall要领直接返回vcvarsall.bat的途径(以本身机械装置后的途径为准)
比方
returnr'C:\Users\Administrator\AppData\Local\Programs\Common\Microsoft\Visual C++ for Python\9.0\vcvarsall.bat'
3、 装置Cython库
pip install Cython
4、编写一个测试代码文件test.py放在D:/test/test.py
然后在统一目次下,新建一个setup.py文件,内容以下:
cythonize()是Cython供应将Python代码转换成C代码的API,
setup是Python供应的一种宣布Python模块的要领。
4. 运用敕令行编译Python代码:
3.上述完成以后就能够在windwos下一般编译python的C扩大。实行以下敕令
python setup.py install
固然也能够竖立一个windows的二进制包:
python setup.py bdist_wininst
固然也能够直接编译到当前目次:
python setup.py build_ext --inplace
build_ext是指明python生成C/C++的扩大模块(build C/C++ extensions (compile/link to build directory))
--inplace指导 将编译后的扩大模块直接放在与test.py同级的目次中。
以上就是windows平台下python生成 pyd文件的细致要领引见的细致内容,更多请关注ki4网别的相干文章!