Python code.compile_command() Function

Python code Module:

The code module contains functions for implementing read-eval-print loops in Python. There are two classes and two convenience functions available that can be used to build applications that give an interactive interpreter prompt.

The code module includes a variety of functions for emulating the behaviour of the standard interpreter’s interactive mode.

The compile command works in the same way as the built-in compile function, but it does some additional checks(tests) to ensure that you provide it with a complete Python statement.

Python code.compile_command() Function:

We can use the code.compile_command() method to compile a single or numerous lines of code in order to check for syntax errors.

Syntax:

 code.compile_command(code)

Return Value:

An object or compilation error if occurred is returned by the compile_command() function.

code.compile_command() Function in Python

 

Method #1: Using compile_command() Function (Static Input)

Approach:

  • Import compile_command function from code module using the import keyword.
  • Give the code as static input and store it in a variable.
  • Pass the above-given code as an argument to the compile_command() function
    to compile the given code.
  • The Exit of the Program.

Below is the implementation:

# Import compile_command function from code module using the import keyword
from code import compile_command

# Give the code as static input and store it in a variable.
code = 'x = 3 y = 4; print(x*y)'

# Pass the above given code as an argument to the compile_command() function
# to compile the given code
compile_command(code)

Output:

 File "<input>", line 1
x = 3 y = 4; print(x*y)
^
SyntaxError: invalid syntax

Method #2: Using compile_command() Function (User Input)

Approach:

  • Import compile_command function from code module using the import keyword.
  • Give the code as user input using the input() function and store it in a variable.
  • Pass the above-given code as an argument to the compile_command() function
    to compile the given code.
  • The Exit of the Program.

Below is the implementation:

# Import compile_command function from code module using the import keyword
from code import compile_command

# Give the code as user input using the input() function and store it in a variable.
code = input("Enter some random code:\n")
print()

# Pass the above given code as an argument to the compile_command() function
# to complie the given code
compile_command(code)

Output:

Enter some random code:
+x=5

File "<input>", line 1
SyntaxError: can't assign to operator