Python's interactive mode works on the principle of REPL (Read - Evaluate - Print - Loop). The code module in Python's standard library provides classes nd convenience functions to set up REPL environment from within Python script.
Following two classes are defined in code module:
InteractiveInterpreter: This class deals with parsing and interpreter state (the user’s namespace)
InteractiveConsole: Closely emulate the behavior of the interactive Python interpreter.
Two convenience functions in the module are:
interact(): Convenience function to run a read-eval-print loop.
compile_command(): This function is useful for programs that want to emulate Python’s interpreter main loop (the REPL).
Interactive Interpreter methods
runsource(): Compile and run some source in the interpreter.
runcode(): Execute a code object
Interactive Console methods:
Because the InteractiveConsole class is a subclass of InteractiveInterpreter, above methods are automatically available. Additionally following methods are defined.
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.
Write a prompt and read a line by defaultfrom sys.stdin
import code x = 10 y = 20 def add(x,y): return x+y print (add(x,y)) code.interact(local=locals()) print (x,y) print (add(x,y))
In the above code, two vaiables are defined and passed to a function. The we invoke he 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, those values are now passed to the function
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