简单记录一下不同 python 文件扩展的含义~
py
最常见,python 源码文件
pyc
编译后的字节码(bytes code)
当我们 import 一个模块的时候,python 根据 py 源文件会生成一个包含字节码的 pyc 文件,使得后续 import 该模块更快。
pyo
当我们使用 python -O 时,则原本生成 pyc 的文件会被改为 pyo 格式。文档中对于 -O 选项的说明:
-O : optimize generated bytecode slightly; also PYTHONOPTIMIZE=x
-OO : remove doc-strings in addition to the -O optimizations
而 python 的 optimizer 目前其实并没有做太多功能,它只是移除了 assert 语句。当使用了 -O 时,.pyc 文件会被忽略,转而生成 optimize bytes code;当使用了 -OO 时,__doc__ 会从字节码中移除,使得生成的文件更加紧凑。
不过,即便 python 生成了 pyc 或 pyo 字节码文件,我们的 python 程序并不会执行得更快,快的只是它们在加载的时候。
另外,当我们从命令行执行一个指定的 python 脚本时,它并不会生成对应的 pyc 或 pyo 文件。因此,我们一般会将其大部分代码封装成模块,而启动脚本间接地导入这些模块。
pyd
这个本质上就是一个 windows 下的 dll 文件,类似玉 unix 的动态链接库 so 文件。那 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 functionPyInit_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 callPyInit_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.
参考:
Add Comment