reddit / emacs

Clear ipython buffer when longer than X lines

wehrad · 2022-02-05 08:22
Hi everyone, ​ My ipython console is getting super slow when the buffer is longer than \~10 000 lines (for example when I accidentally print a very long variable). I know C-c M-o runs the command comint-clear-buffer (found in inferior-python-mode-map), which is an interactive compiled Lisp function. And running it manually solves my problem. Now, I would like to have it to run automatically when the \*Python\* buffer is longer than X lines, but can't find how to do it. One related issue is that I shouldn't run into a long buffer limitation than quickly, i.e. I should prevent very long variables (e.g. long lists) from being entirely printed in the buffer. For instance, when print() is called, I would like to only print the first and last 10 entries of a variable if it is longer than e.g. 100 lines. However, here again, I can't find how to do it... ​ Any help would be much appreciated, thank you a lot in advance! :)
sebhoagie · 2022-02-05 08:42
I am on mobile but one idea is to look for some hook in comint or Python's interactive mode that is called before inserting the output in the buffer, so you have a chance of reducing it.
mickeyp · 2022-02-05 12:19
You can set `comint-buffer-maximum-size` to a number of maximum bytes. Emacs'll truncate the buffer if it exceeds that amount. Not sure there's a builtin option for *lines*, but I use this setting myself and it's good enough for my use cases.
JDRiverRun · 2022-02-05 22:07
It's probably the very long lines causing the slow-down (try `M-x so-long` next time it's very slow and you can check this). But iPython has a pretty printer built-in. You could run: % ipython --PlainTextFormatter.max_seq_length=10 Python 3.10.0 (default, Oct 13 2021, 06:45:00) In [1]: long_list = list(range(50000)) In [2]: long_list Out[2]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, ...]