Python is a dynamic language, and running it from the command line essentially triggers the following steps:
- The source is compiled the first time it is encountered (e.g., imported as a module or directly executed). This step generates the binary file, with a .
pyc or .pyo extension depending on your system. - The interpreter reads the binary file and executes the instructions (opcodes) one at a time.
The python interpreter is stack-based and once source is compiled corresponding .pyc are ready in the same directory (in case of python 2.x). With python 3.x a new __pycache__ directory is created for the source and all compiled Bytecode files are placed underneath.
If you want to manually compile a module or generate its compiled bytecode you can consider using py_compile module 32.10. py_compile - Compile Python source files - Python 2.7.11 documentation.
SAMPLE:
>>> import py_compile
>>> py_compile.compile('http://abc.py')
Once source is compiled you might be further interested in inspecting bytecode. For this purpose cpython proved a module called dis 32.12. dis - Disassembler for Python bytecode - Python 2.7.11 documentation (python disassembler) which comes quiet handy while trying to understand bytecode.
A SAMPLE:
>>> def foo():
... a = 2
... b = 3
... return a + b...
>>> foo.func_code
<code object foo at 0x106353530, file "<stdin>", line 1
>>>> foo.func_code.co_code
'd\x01\x00}\x00\x00d\x02\x00}\x01\x00|\x00\x00|\x01\x00\x17S'
>>> print [ord(x) for x in foo.func_code.co_code]
[100, 1, 0, 125, 0, 0, 100, 2, 0, 125, 1, 0, 124, 0, 0, 124, 1, 0, 23, 83]
>>>
>>>
>>> import dis
>>> dis.dis(foo)
2 0 LOAD_CONST 1 (2)
3 STORE_FAST 0 (a)
3 6 LOAD_CONST 2 (3)
9 STORE_FAST 1 (b)
4 12 LOAD_FAST 0 (a)
15 LOAD_FAST 1 (b)
18 BINARY_ADD
19 RETURN_VALUE
I hope it helps !