0

I want to get history count (and contents) from Python.

From command line it's possible with readline module (installed via pip install pyreadline):

import readline
x=readline.get_current_history_length()
x

Yields 2, as it should. However the same code using Python C API always returns zero, regardless of actual history:

#include <Python.h>

long GetHistoryCount() {
    Py_Initialize();
    PyRun_SimpleString("import readline");
    PyRun_SimpleString("x=readline.get_current_history_length()");

    PyObject *mainModule = PyImport_AddModule("__main__");
    PyObject *var = PyObject_GetAttrString(mainModule, "x");

    Py_Finalize();
    return PyLong_AsLong(var);
}

int main(int argc, char **argv) {
    long count = GetHistoryCount();
    printf("Count: %ld", count);
    return EXIT_SUCCESS;
}

Prints: Count: 0

How can I get history from Python C API?

Found readline module in this discussion

rfg
  • 1,331
  • 1
  • 8
  • 24
  • Hm, how should the history count be anything else than 0? Is there a history file which is read on startup automatically? With the C readline API a history file is _not_ read automatically, but only on specific request (`read_history()`) – Ctx Dec 28 '18 at 13:34
  • It's Python interpreter history, not OS history. For normal Python invocation (via Python interpreter) it works without specifying files. – rfg Dec 28 '18 at 13:36
  • Yes, of course, but you do not invoke a python interpreter here. So, where should history entries come from? – Ctx Dec 28 '18 at 13:39
  • I thought python context executed lines somewhere. – rfg Dec 28 '18 at 13:41
  • I think, your main misunderstanding here is, that `PyRun_SimpleString()` does _not_ use the readline interface, but passes the command directly to the interpreter. So the commands executed with this function will not be inserted into the readline history. – Ctx Dec 28 '18 at 13:42
  • You could, however, add each command to the readline history manually by invoking `readline.add_history("some command")` for each command. But you have to be cautios to properly escape the command first. – Ctx Dec 28 '18 at 13:47
  • Thank you! Maybe there's a way to add interpreter callback for that, or some setting? – rfg Dec 28 '18 at 13:55

0 Answers0