作者:大永8899_226 | 来源:互联网 | 2023-09-17 14:04
本文问题来源于stackoverflow,原文链接Whatdoespythonfileextensions,.pyc.pyd.pyostandfor?这些python文件后缀是什
本文问题来源于stackoverflow,原文链接
What does python file extensions, .pyc .pyd .pyo stand for?
这些 python 文件后缀是什么含义?
他们之间有什么不同,他们是怎么从一个 *.py 文件产生的?
2 答案
.py
: 这个是你编写的源文件。
.pyc
: 这是编译过的二进制代码文件. 如果你导入一个模块, python 将创建一个 *.pyc
文件,文件中内为二进制码,这样可以在再次导入时更容易(更快)。
.pyo
: 这是一个当优化等级 (-O
) 开启时生成的 *.pyc
文件。
.pyd
: 这个相当于一个 windows dll 文件. http://docs.python.org/faq/windows.html#is-a-pyd-file-the-same-as-a-dll
关于 .pyc
和 .pyo
更深入的探讨,请移步这里: http://www.network-theory.co.uk/docs/pytut/CompiledPythonfiles.html (以下是其中比较重要的部分)
- 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.
- Passing two -O flags to the Python interpreter (-OO) will cause the bytecode compiler to perform optimizations that could in some rare cases result in malfunctioning programs. Currently only docstrings are removed from the bytecode, resulting in more compact ‘.pyo’ files. Since some programs may rely on having these available, you should only use this option if you know what you're doing.
- A program doesn't run any faster when it is read from a ‘.pyc’ or ‘.pyo’ file than when it is read from a ‘.py’ file; the only thing that's faster about ‘.pyc’ or ‘.pyo’ files is the speed with which they are loaded.
- When a script is run by giving its name on the command line, the bytecode for the script is never written to a ‘.pyc’ or ‘.pyo’ file. Thus, the startup time of a script may be reduced by moving most of its code to a module and having a small bootstrap script that imports that module. It is also possible to name a ‘.pyc’ or ‘.pyo’ file directly on the command line.
*.pyd 文件和 DLL一样吗?
是的, .pyd 文件就是 dll’, 但是有一些不同之处。
关于这个问题的回答,python官网有详细的回答:
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 initfoo(). 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 initfoo() 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.