Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Interpreter base classes in Python
Python's interactive mode works on the principle of REPL (Read - Evaluate - Print - Loop). The code module in Python's standard library provides classes and convenience functions to set up REPL environment from within Python scripts.
Core Classes in the Code Module
The code module defines two main classes:
InteractiveInterpreter: This class deals with parsing and interpreter state (the user's namespace).
InteractiveConsole: Closely emulates the behavior of the interactive Python interpreter and is a subclass of InteractiveInterpreter.
Convenience Functions
interact(): Convenience function to run a read-eval-print loop.
compile_command(): Useful for programs that want to emulate Python's interpreter main loop (the REPL).
InteractiveInterpreter Methods
runsource(): Compile and run some source in the interpreter.
runcode(): Execute a code object.
InteractiveConsole Methods
Since InteractiveConsole is a subclass of InteractiveInterpreter, it inherits the above methods. Additionally, it defines:
interact(): Closely emulate the interactive Python console.
push(): Push a line of source text to the interpreter.
resetbuffer(): Remove any unhandled source text from the input buffer.
raw_input(prompt=""): Write a prompt and read a line by default from sys.stdin.
Example
Here's how to create an interactive console within your Python script ?
import code
x = 10
y = 20
def add(x, y):
return x + y
print("addition =", add(x, y))
code.interact(local=locals())
print(x, y)
print("addition =", add(x, y))
In the above code, two variables are defined and passed to a function. Then we invoke the interactive console. The argument local=locals() allows use of local namespace as the default within the interpreter loop.
If you assign different values to variables and exit the console by pressing Ctrl+D (Linux/Mac) or Ctrl+Z (Windows), those modified values are now available to the rest of the script.
Output
addition = 30 Python 3.6.6 |Anaconda custom (64-bit)| (default, Oct 9 2018, 12:34:16) [GCC 7.3.0] on linux Type "help", "copyright", "credits" or "license" for more information. (InteractiveConsole) >>> x = 100 >>> y = 200 >>> now exiting InteractiveConsole... 100 200 addition = 300
Creating a Custom Interactive Console
You can also create a custom interactive console by subclassing InteractiveConsole ?
import code
class CustomConsole(code.InteractiveConsole):
def __init__(self, locals=None):
super().__init__(locals)
self.prompt = "custom>>> "
def interact(self, banner="Welcome to Custom Python Console"):
super().interact(banner)
# Create and use custom console
console = CustomConsole(locals={'x': 42})
print("Starting custom console...")
# console.interact() # Uncomment to run interactively
Starting custom console...
Conclusion
The code module provides powerful tools for embedding interactive Python interpreters within your applications. Use InteractiveConsole for full REPL functionality and InteractiveInterpreter for custom parsing and execution control.
