Search code examples
pythonconsole

Enabling console features with code.interact


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?


Solution

  • 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()