Why does exiting Python REPL clear my Ctrl-V Bash mapping?

I can not reproduce the problem that leaving REPL python changes lnext.
But I can confirm that you need to source a file twice to get the bind key to work (the output of mapping works).

Note that you need to start a logging bash session to get .bash_profile to be read. A file like:

$ cat ~/.bash_profile
echo bash_profile read
#stty lnext ^-
stty lnext ''

Will only work if bash is called like bash -l for example. Just check that you get bash_profile read when you start bash.

Solution:

The best bet is to set the key binding in the file ~/.inputrc:

$ cat ~/.inputrc
#bind -x '"\C-v": "echo mapping works"'
\C-v: "echo mapping works\C-m"

Then, the binding could be read in with Ctrl-x Ctrl-r, nothing else is needed, as soon as that is executed the key binding works in bash. And, it will be read when bash start.

If you still need to remove the same keybinding in the tty:

$ cat ~/.bash_profile
echo bash_profile read
#stty lnext ^-
stty lnext ''

Using lnext '' works more consistently IME. Remove or comment the echo when needed.

Added
There is no way to (exactly) mimic the bind -x way of executing shell commands.

But what is a command ?, but an string that ends with an enter.
Place this on the ~/.inputrc

\C-v: "echo 'yes\!. It works.'\n"

Re-read the ~/.inputrc file and try \C-v.
Note that (IME) it is better to use \C-m.

If you want the line cleared before typing the command, use

\C-v: "\C-e\C-x\C-?echo 'yes\!. It works.'\C-m\C-y"

But, bear in mind that more complex bindings have more probability to fail for unknown reasons. Just try it, maybe it will work for you. If it does, the only difference with the normal bind -x is that the command executed gets into the history (nothing important IMhO).

Related:

  • Shell Tricks: .inputrc binding fun
  • In bash, how do I bind a function key to a command?