Explain how Python is an interpreted language

Python is a general-purpose interpreted, interactive, object-oriented, and high-level programming language. Python is processed at runtime by the interpreter. You do not need to compile your program before executing it. This is similar to PERL and PHP.

Steps of Execution

Step1 − A Python source code is written by the coder. File extension: .py

Step 2 − The Python source code a coder writes is compiled into python bytecode. In this process, a file with the extension .pyc gets created.

Step 3 − The Virtual Machine executes the .pyc extension file. Consider the Virtual Machine is the runtime engine of Python. This is where the Python program runs.

Therefore, the Python Interpreter includes the process of Program Compilation, which in-turn compiles into bytecode, then the execution by Virtual Machine.

Let us see the following illustration to understand the execution process in a better way

Create a .pyc file

To create a .pyc file in Python, use the PyCompile. The official documentation even suggests the same as shown below −

The py_compile module

The py_compile module provides a function to generate a byte-code file from a source file, and another function used when the module source file is invoked as a script. The py_compile.compile() compile a source file to byte-code and write out the byte-code cache file.

Now, let us see the example −

import py_compile py_compile.compile("demo.py")

Use the py_compile.main()

import py_compile py_compile.main(['File1.py','File2.py','File3.py'])

The compileall module

The compileall module provides some utility functions to support installing Python libraries. These functions compile Python source files in a directory tree. This module can be used to create the cached byte-code files at library installation time, which makes them available for use even by users who don’t have write permission to the library directories.

You can also compile from the command line using the compileall module −

python -m compileall <file_1>.py <file_n>.py

Compile every single file in the mentioned directory. The compile_dir() recursively descend the directory tree named by dir, compiling all .py files along the way. Return a true value if all the files compiled successfully, and a false value otherwise −

import compileall

Use compileall.compile_file(): The compile_file() method compile the file with path fullname. Return a true value if the file compiled successfully, and a false value otherwise:

import compileall