py/pyc/pyo/pyd 的区别以及pythonw

py/pyc/pyo/pyd 的区别以及pythonw

Mar 3, 2014
Coding
Python

pythonw.exe 和 python.exe #

使用python.exe 执行脚本时会出现黑窗口,使用pythonw.exe执行脚本时则不会出现。

比如在某些Python IDE中,如果解释器使用python.exe则每次执行时会弹出python脚本运行的黑窗口,使用pythonw.exe则不会出现。

其它方面,两者没有区别。

If you don’t want a terminal window to pop up when you run your program use pythonw.exe; Otherwise, use python.exe。

摘自 StackOverflow: pythonw.exe or python.exe

py/pyc/pyo/pyd的区别 #

  • .py: python 脚本文件(source code)
  • .pyc: 脚本文件编译得到的字节码
  • .pyo: 脚本文件开启优化编译选项(-O)编译得到的字节码
  • .pyd: 基本的Windows DLL文件

pyc 和pyo 不会提高代码执行速度,只会提高代码的加载速度。

python并非完全是解释性语言,它是有编译的,先把源码py文件编译成pyc或者pyo,然后由python的虚拟机执行,相对于py文件来说,编译成pyc和pyo本质上和py没有太大区别,只是对于这个模块的加载速度提高了,并没有提高代码的执行速度,通常情况下不用主动去编译pyc文件,文档上说只要调用了import model那么model.py就会先编译成pyc然后加载。

此段摘自 只想简单的博客 python的pyc和pyo文件

  1. .py: This is normally the input source code that you’ve written.
  2. .pyc: This is the compiled bytecode. If you import a module, python will build a *.pyc file that contains the bytecode to make importing it again later easier (and faster).
  3. .pyo: This is a *.pyc file that was created while optimizations (-O) was on.
  4. .pyd: This is basically a windows dll file. http://docs.python.org/faq/windows.html#is-a-pyd-file-the-same-as-a-dll

Also for some further discussion on .pyc vs .pyo, take a look at: http://www.network-theory.co.uk/docs/pytut/CompiledPythonfiles.html (I’ve copied the important part below)

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.

摘自 StackOverflow: What does python file extensions, .pyc .pyd .pyo stand for?