When the Python interpreter is invoked with the -O flag, optimized code is generated and stored in .pyo files. The optimizer currently doesn’t help much; it only removes assert statements. When -O is used, all bytecode is optimized; .pyc files are ignored and .py files are compiled to optimized bytecode.
Python 是一种胶水语言,我们可以将对速度要求比较高的那一部分代码使用 C 语言编写,编译成动态链接库文件,再通过 Python 来调用。一般来说,在 Linux 上是 so文件,在 Windows 系统上是DLL文件。
例如有一个 C 语言编写的 Windows 动态链接库 test_lib.dll,编译前的代码如下:
intsum(int x,int y) {
return x + y; }
我们可以在 Python 代码中通过下面的方式来调用
# test_lib.dll 放在当前目录下 import ctypes from ctypes import* test_lib = ctypes.windll.LoadLibrary("test_lib.dll") a = ctypes.c_int(1) b = ctypes.c_int(2) out = test_lib.sum(a, b) print(out)# 3
在 Windows 系统上,Python 还有一种 pyd格式的动态链接库,上面的调用方式是先通过ctypes.windll.LoadLibrary 方法将动态链接库加载进来,而pyd格式就可以在 Python 代码中直接import进来,类似下面这样:
# test_lib.pyd 放在当前目录下 import test_lib out = test_lib.sum(1,2) print(out)# 3
关于 pyd文件和dll文件的区别,可参考官方文档的说明:
Is a *.pyd file the same as a DLL?
Yes, .pyd files are dll’s, but there are a few differences. If you have a DLL named foo.pyd, then it must have a function PyInit_foo(). You can then write Python “import foo”, and Python will search for foo.pyd (as well as foo.py, foo.pyc) and if it finds it, will attempt to call PyInit_foo() to initialize it. You do not link your .exe with foo.lib, as that would cause Windows to require the DLL to be present.
Note that the search path for foo.pyd is PYTHONPATH, not the same as the path that Windows uses to search for foo.dll. Also, foo.pyd need not be present to run your program, whereas if you linked your program with a dll, the dll is required. Of course, foo.pyd is required if you want to say import foo. In a DLL, linkage is declared in the source code with __declspec(dllexport). In a .pyd, linkage is defined in a list of available functions.
C 语言代码和 Python 代码都可以通过一定的方法编译成pyd格式的文件,本人并没有实际使用过pyd文件,详细方法可参考下面的文章: