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
Active
Viewed 1,565 times
2

l k
- 117
- 8
-
That should work by default with `code.interact()`. If it doesn't, you may be using two different Python installations or something. – user2357112 Jun 18 '18 at 21:55
1 Answers
16
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()

Romuald Brunet
- 5,595
- 4
- 38
- 34

Sunitha
- 11,777
- 2
- 20
- 23
-
Turns out there was something messed up in my installation so the `readline` module wasn't available. Just fixing that problem made it work, thanks for the pointer in the right direction. – l k Jun 18 '18 at 22:15
-
@xaxxon. Sorry; it should be "locals()". It is optional and is needed if you want the local variables visible in the new interactive session you launch – Sunitha Jul 24 '19 at 06:20
-
2I needed the `readline.set_completer(rlcompleter.Completer(vars).complete)` to get tab completion to work. Especially if I set custom contexts, then it would not recognize those with tab completion, only the builtin ones. Thank you. – E. Körner Jan 09 '21 at 18:00
-
But the readline wouldn't work any more if I entered an invalid command in the intractive python shell.Any idea to solve this? – 傅继晗 Feb 13 '21 at 13:18
-
Note that on mac os you may need to run `readline.parse_and_bind("bind ^I rl_complete")` instead of the same function call on "tab: complete" - see https://stackoverflow.com/questions/71229303/how-does-djangos-python-manage-py-shell-keep-the-command-prompt-open/71230433#71230433 which checks for use of libedit – Nick Meyer Mar 29 '23 at 23:17