Enabling console features with code.interact

Question:

If I start a new Python interactive session from the command line, some console features such as using the arrow keys to access a previous command, etc. are present.
If instead, however, I use code.interact() to start an interactive session from inside a larger script, the escape sequences aren’t properly handled – e.g. pressing the ⮹ key prints ^[[A instead of displaying the previous command. How do I enable this feature?

Asked By: l k

||

Answers:

You can use readline module to get arrow keys working

import code
import readline
import rlcompleter
           
vars = globals()
vars.update(locals())
                                              
readline.set_completer(rlcompleter.Completer(vars).complete)
readline.parse_and_bind("tab: complete")
code.InteractiveConsole(vars).interact()
Answered By: Sunitha
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.