What is Python Interpreter – Environment, Invoking & Working
Master Python with 70+ Hands-on Projects and Get Job-ready - Learn Python
In this Python Interpreter tutorial, you will see what is Python interpreter, how to invoke it, and how does it work.
Moreover, we will discuss the environment and features of Interpreter of Python Programming Langauge.
So, let’s start the Python Interpreter Tutorial.
Python Interpreter & its Environment (Source Code Encoding)
The default encoding for a Python source file is UTF-8. This is a Unicode Standard variable-width character encoding; it can encode 1,112,064 valid code points in Unicode using up to four 8-bit bytes.
Using this encoding, we can use characters of most languages – we can use these in string literals, comments, and identifiers.
Since the standard library makes use of ASCII characters only, you must declare the use of this encoding to your editor.
This is to ensure that all such characters display without a problem. The font should be such that supports all characters in the file.
We add this comment as the first line of the file we want to use it in-
# -*- coding: encoding -*-
In this, encoding is a valid codec that Python supports.
Similarly, when you want to use the Windows-1252 encoding, you can use this as the first line of code:
# -*- coding: cp1252 -*-
However, when you want to begin code with a UNIX shebang line, you can put the comment for encoding second-
#!/usr/bin/env python3 # -*- coding: cp1252 -*-
How to Invoke the Python Interpreter?
On your machine, you can find your interpreter at an address like:
C:\Python36
Or it may reside on the location you selected at the time of installation. Add path using this command:
set path=%path%;C:\python36
Start the Python Interpreter
On Windows, when you want to run the Python interpreter in the shell, you can type the following:
$python
To get out of the interpreter in disassembling the Bytecode shell, you can type:
>>> quit()
Output
Alternately, you can use an end-of-file character at the prompt.
Python interpreter exits with a zero exit status. You can use it in a REPL (Read-Evaluate-Print-Loop) fashion.
But if you want, you can save your Python code as a script and execute it using the interpreter:
$python demo.py
To enter interactive mode after running a script, you can pass –i before the script.
The command python -c command [arg] … executes statements in command, and python -m module [arg] … executes the source file for the module.
Features of Python Interpreter
Python interpreter offers some pretty cool features:
- Interactive editing
- History substitution
- Code completion on systems with support for readline
In the first Python prompt, try pressing the following keys:
Ctrl+P
This tells you if your interpreter supports command-line editing. A beep indicates that it does support command-line editing.
Otherwise, it will either perform a no-operation or echo ^p to indicate it isn’t available.
Passing Arguments in Python
When you pass a script name and additional arguments to the shell when invoking the Python interpreter, it turns these into a list of strings.
Then, it assigns these to the variable argv in the sys module.
The following command will give us a list of this-
import sys
Without a script or arguments, sys.argv[0] denotes an empty string.
A script name of ‘-‘ means that it sets sys.argv[0] to ‘-‘, and with ‘-c’, it is set to ‘-c’. A value of ’-m’ sets sys.argv[0] to the module’s full name.
The command/ module handles the options after ‘-c’ or ‘-m’.
Interactive Mode in Python
Python interpreter is in an interactive mode when it reads commands from a tty.
The primary prompt is the following:
>>>
When it shows this prompt, it means it prompts the developer for the next command. This is the REPL.
Before it prints the first prompt, Python interpreter prints a welcome message that also states its version number and a copyright notice.
This is the secondary prompt:
…
This prompt denotes continuation lines.
$ python3.7 Python 3.7 (default, Jul 16 2018, 04:38:07) [GCC 4.8.2] on Windows Type "help", "copyright", "credits" or "license" for more information. >>>
You will find continuation lines when working with a multi-line construct:
>>> it_rains =True >>> if it_rains: print("The produce will be good")
Output
You can also use the Python interpreter as a calculator:
>>> 2*7 14 >>> 4/2 2.0
How Does Python Interpreter Works?
Well, internally, four things happen in a REPL:
i. Lexing- The lexer breaks the line of code into tokens.
ii. Parsing- The parser uses these tokens to generate a structure, here, an Abstract Syntax Tree, to depict the relationship between these tokens.
iii. Compiling- The compiler turns this AST into code object(s).
iv. Interpreting- The interpreter executes each code object
1. Function Objects & Code Objects in Python
When we talk of function objects, we mean to say that in Python, functions are first-class objects (functions indeed are objects).
You can pass them around and talk about them without making a call to them.
>>> def bar(a): x=3 return x+a >>> bar
Output
Now bar.__code__ returns a code object:
>>> bar.__code__ <code object bar at 0x107eeccb2, file "<stdin>", line 1>
So, we conclude that a code object is an attribute of a function object. The dir() function will tell us more about the function:
>>> dir(bar.__code__)
Output
‘__getattribute__’, ‘__gt__’, ‘__hash__’, ‘__init__’, ‘__le__’, ‘__lt__’, ‘__ne__’, ‘__new__’,
‘__reduce__’, ‘__reduce_ex__’, ‘__repr__’, ‘__setattr__’, ‘__sizeof__’, ‘__str__’,
‘__subclasshook__’, ‘co_argcount’, ‘co_cellvars’, ‘co_code’, ‘co_consts’, ‘co_filename’,
‘co_firstlineno’, ‘co_flags’, ‘co_freevars’, ‘co_lnotab’, ‘co_name’, ‘co_names’, ‘co_nlocals’,
‘co_stacksize’, ‘co_varnames’]
This gives us the attributes of the code object. Values of some more attributes:
>>> bar.__code__.co_varnames
Output
>>> bar.__code__.co_consts
Output
>>> bar.__code__.co_argcount
Output
2. Bytecode in Python
The following command gives us the bytecode:
>>> bar.__code__.co_code
Output
This is a series of bytes, each of which the interpreter loops through and then makes an execution.
3. Disassembling the Bytecode
We will use the dis() method from the dis module to understand what’s going on- this isn’t part of what the interpreter does.
>>>import dis >>> dis.dis(bar.__code__)
Output
3 STORE_FAST 1 (x)
3Â Â Â Â Â Â Â 6 LOAD_FAST 1 (x)
9 LOAD_FAST 0 (a)
12BINARY_ADD
13RETURN_VALUE
In this, the first set of numbers is the line numbers in the actual code. The second one depicts offsets of the bytecode.
Then comes the set of names for the bytes- for human readability.
The next column depicts the arguments and the last column lists the constants and names in the fourth column.
>>> bar.__code__.co_consts[1]
Output
>>> bar.__code__.co_varnames[1]
Output
So, this was all about Python Interpreter Tutorial. Hope you like our explanation.
Conclusion
Hence, we can say the compiler for Python generates bytecode for the interpreter. The Python interpreter uses this with the virtual machine.
The same bytecode doesn’t always end up doing the same things. This is another thing that makes Python dynamic.
Also, the default prompt for the interpreter is >>>.
Did you like this article? If Yes, please give DataFlair 5 Stars on Google
When we simply write
python test.py
It will simply interpret it(convert from source code to machine code and execute it)
But when we compile it:
compile(test.py)
It will be compiled(convert source code into byte code).
Then PVM will further execute it using interpreter.
Is it like this if I am not wrong.
“Hi Jatinder,
We are so grateful for your feedback on “Python Interpreter”. Here, we solve your query-
Talking about the internals of Python, the PVM (Python Virtual Machine) executes the intermediate code that results from your source code.
Everytime we call a Python program, Python creates a compiled version with .pyc extension if it doesn’t already exist.
To compile a Python program manually, you can do either of the following-
1. Import the py_compile module with the interpreter:
>>> import py_compile
>>> py_compile.compile(‘test.py’)
2. Use the following command at the shell prompt:
python -m py_compile test.py
This will create a new subdirectory- ‘__pycache__’ with file ‘test.cpython-37.pyc’ in it.
This is the byte code; it is the compiled result. You can also try using the compileall module to compile all Python files.”
Python
As per my understanding , what is the difference between compiler and interpreter ? Is python a compiler or interpreter language or both ?
>> Python is both , first it compiles during compilation it creates a .pyc file here i didnt understand what is the purpose of .pyc file what exactly it does ?
>> Once the compilation is done it then interprete , so what is interpreter .. the line by line execution …please correct me if I am wrong and please let me know what was the exact difference ? How internally the code executes in python ?
La principal defirencia es que el interprete va traduciendo linea a linea y en vivo el programa, encambio el compilador lo hace todo el programa de una vez, y si hubo un error tienes que volver a traducir todo e intentar nuevamente resolverlo, espero que te ayude con tu duda.
Compiler converts high level language code to machine code in one go and then starts the execution on the other hand, interpreter takes high level code line by line and converts it to machine code, executes it and then takes another line.
Python is compiled first not directly into machine code but into bytecode and then that is either interpreted (as in CPthon) or both interpreted and compiled (as in PyPy).
Is not clear where i must write the sys.argv In the video it doesn’t say anything