When using the Python Interpreter, is the compiler used at all?

In Google's Python Class it reads

Python is a dynamic, interpreted (bytecode-compiled) language

I know what an interpreter is and know what bytecode is but the two together seem not to fit. After doing some reading it became a bit clearer that basically Python source code is automatically compiled before it is interpreted; but some new questions emerged.

When using the Python Interpreter does no compilation happen? If it does, when? For example if you're just typing code at the command line and it gets run each time you hit enter, when does a compiler have the opportunity to do its work?

Also in the linked to question above, @delnan gives a pretty broad definition of a compiler

A compiler is, more generally, a program that converts a program in one programming language into a program in another programming language...JIT compilers compile to native machine code at runtime

I guess my question is: what's the difference between an interpreter and automatic compiler? To refine the question a bit, if Python is compiled, why not compile all the way to machine code (or assembly, since I know writing compilers that can produce pure machine code is difficult)?


Perhaps it is best to forget semantics and just try to learn what Cpython is actually doing. When you invoke the Cpython binary, it does a number of things. Generally speaking, you can expect it to translate the code you've written into a sequence of bytecode instructions. This is the "compiling" stage that people will sometimes reference for python code. These are a more compact and efficient way to tell the interpreter what to do than your hand-written code. Frequently, python will cache these files for reuse in .pyc files (only re-generating if the associated .py file is newer). You can think of python bytecode as the set of instructions that the python virtual machine can run -- In a lot of ways, it's not really all that different than what you get for Java. When people speak of compiled languages (eg C ), the compiler's job is to translate your code into a set of instructions that will run directly on your computer's hardware. Languages like Cpython and Java have an extra level of indirection (eg the Virtual Machine). The Virtual Machine runs directly on the computer's hardware and is responsible for interpreting the domain specific language.

Compared to standard "compiled" languages (eg C , Fortran ), this stage is really light-weight -- and python doesn't do a lot of the checking that "traditional" compilers will do (eg typechecking). It pretty much only checks the syntax and does a few very simple optimizations using the peephole optimizer.

链接地址: http://www.djcxy.com/p/52564.html

上一篇: PHP解释器Opcache

下一篇: 在使用Python解释器时,编译器是否可以使用?