How does the python interpreter run code line by line in the following code?

I read that the interpreter runs the code line by line and reports an error if it is at the same time, and stops further execution. So in python, consider the ex1.py file,

 print "Hello world" 12variable = 'bye' print 12variable 

Now, in accordance with the work of the interpreter, the interpreter will start the first line, that is, first prints the world hello, and then displays a syntax error in the next line (in turn). Therefore, the expected result:

 Hello world 12variable = 'bye' ^ SyntaxError: invalid syntax 

But the actual conclusion is

 12variable = 'bye' ^ SyntaxError: invalid syntax 

Why doesn't he print Hello World in the first place?

+6
source share
4 answers

It depends on how you run Python interpréter. If you give it the full source file, it will first analyze the entire file and convert it to bytecode before executing any command. But if you feed him in turn, he will analyze and execute the block of code block:

  • python script.py : python script.py full file
  • python < script.py : python < script.py and execute in block

The latter, as a rule, is used interactively or through the shell of a graphical interface, for example idle .

+5
source

It is a myth that Python is a fully interpreted language. When CPython runs the script, the source code is analyzed (here it will catch syntax errors) and compiled into bytecode (sometimes they are cached in your directory as .pyc files) before anything is executed. In this regard, Python is not everything that is fundamentally different from Java or C #, except that it does not spend much time on any optimizations, and I believe that the byte code is interpreted one command at a time, instead of to be JITed by machine code (unless you are using something like PyPy).

+5
source

Because your understanding of the translator is wrong. Although it is possible that the behavior you describe for a specific subset of errors is not a common case for many (most?) Errors.

If the interpreter can build what, in its opinion, is a valid program, but there is an error at runtime, then what you describe will happen.

Since the case you are pointing out is a syntax error that prevents the creation of a reliable program, the behavior is the way you see it.

+2
source

As I understand it:

Python runs line-by-line code after in a byte-code state.

The difference between this thing and compilation (in other languages ​​such as C ++) is that you have to perform this interpretation process every time you run the script.

The Python interpreter interprets the code each time the script runs.

In C ++, you compile a program, and you can execute it without having to compile it if you do not want to change the system.

0
source

All Articles