CPython疑问:为何3行脚本执行需要远超3次解释器循环?
Great question! Let me break down exactly why you're getting a flood of "hello" messages before the output 3—it all comes down to what that for (;;) loop in ceval.c actually does, and how much work CPython does behind the scenes to run even a tiny script.
First, let's clarify the loop's role
That infinite loop in Python/ceval.c is CPython's bytecode execution main loop. Every single iteration of this loop runs exactly one bytecode instruction. So every time CPython executes any bytecode (whether from your script or its own internal code), it prints "hello".
Your 3-line script is just the tip of the iceberg
While your test.py compiles to only a handful of bytecode instructions (you can verify this with the dis module in Python 2.7), CPython does way more work than just executing those few lines:
- Startup initialization: When you launch Python, it first sets up its entire runtime environment. This includes loading built-in modules (like
__builtin__, which contains theprintfunction), initializing memory managers, and setting up the interpreter state—all of which involves executing thousands of internal bytecode instructions. - Script compilation: Before running your
test.py, CPython has to compile the source code into bytecode. In Python 2.7, the compiler itself is implemented in Python, so compiling your script means running even more bytecode under the hood. - Under-the-hood operations for your code: When executing
print X + Y, CPython doesn't just run the few bytecodes for loadingX,Y, adding them, and callingprint. It has to handle object lookups, invoke the addition operator, manage I/O for the print statement, and handle any cleanup afterward—each of these steps triggers additional bytecode execution.
A quick test to prove this
If you create an empty empty.py file and run it with your modified CPython, you'll still see a ton of "hello" messages. That's because all the startup and initialization work happens even when there's no user code to run.
So the "hello" lines aren't coming from your script's bytecode alone—they're from every single bytecode instruction CPython executes during its entire lifecycle while handling your script.
内容的提问来源于stack exchange,提问作者my_question

