I am running my python script through the gdb via gdb -x py_script.py.
The only program I can't seem to be able to work around is the fact that editing and history of the built-in python readline module is broken when I try Ctrl + P, etc.
Here is a simple script:
import readline
while True:
_in = input("_in: ")
print(readline.get_current_history_length()) # always 0
print('out:', _in)
I have done some research on gdb.sys.stdin, gdb.sys.stdout, gdb.sys.stderr. However, using these directly won't cut it.
Please, let me know if there is an approach that would work. For example, overwritting sys.stdin or similar.
Also see, the following quote at https://sourceware.org/gdb/current/onlinedocs/gdb.html/Basic-Python.html#Basic-Python.
At startup, GDB overrides Python’s sys.stdout and sys.stderr to print using GDB’s output-paging streams. A Python program which outputs to one of these streams may have its output interrupted by the user (see Screen Size). In this situation, a Python KeyboardInterrupt exception is thrown.
In fairness, there is no clear/practical use case of input() in a gdb session that I could dig up so it might not be worth bringing up - given that people would probably just implement their own GDB commands instead of using Python input. For example,
import gdb
class AskCmd(gdb.Command):
def __init__(self):
super().__init__("ask", gdb.COMMAND_USER)
def invoke(self, arg, from_tty):
print("You typed:", arg)
AskCmd()
Thank you all in advance.
After continuously digging, I have, at last, found a very useful discussion on IPython + gdb and resetting the sys.stdout and sys.stderr to the built-in ones did the wonders here.
I did already try this. However, I wasn't sure how to get the actual built-in and sys.__stdout__.
StackOverflow question: How can I use IPython interactive shell in gdb? || How can I get tab-completion to work in gdb's Python-interactive (pi) shell?
Here is the code now:
import sys
sys.stdout = sys.__stdout__
sys.stderr = sys.__stderr__
# load readline
import readline
while True:
_in = input("_in: ") # Editing and history now enabled!
print(readline.get_current_history_length()) # returns the incremented number after each input. OK!
print('out:', _in)