summary refs log tree commit diff
path: root/dot_ipython/profile_default/startup/80_pandas.py
diff options
context:
space:
mode:
authorAlen <alen@dotfiles.xyz>2023-09-25 21:32:05 +0400
committerAlen <alen@dotfiles.xyz>2023-09-25 21:32:05 +0400
commit4b8ed94012af1fb4f4752b5d199f79c6bcfd4c59 (patch)
treead54d702d385e973f367cc02c9115b1948510caa /dot_ipython/profile_default/startup/80_pandas.py
parent33df3ffbe31ea3b722bfeec21e6a4ebfd038aa00 (diff)
Add basic IPython config and startup scripts
Diffstat (limited to 'dot_ipython/profile_default/startup/80_pandas.py')
-rw-r--r--dot_ipython/profile_default/startup/80_pandas.py70
1 files changed, 70 insertions, 0 deletions
diff --git a/dot_ipython/profile_default/startup/80_pandas.py b/dot_ipython/profile_default/startup/80_pandas.py
new file mode 100644
index 0000000..be18869
--- /dev/null
+++ b/dot_ipython/profile_default/startup/80_pandas.py
@@ -0,0 +1,70 @@
+"""Pandas utilities."""
+
+
+def _setup():
+    import logging
+    import time
+    import fcntl
+    import struct
+    import termios
+    import threading
+
+    class PandasResizer(threading.Thread):
+        """Pandas width/max_row resizer depending on tty size."""
+
+        def __init__(self, max_rows=200):
+            self.max_rows = max_rows
+            self.width = None
+            self.logger = logging.getLogger("startup.pandas")
+            self._run = False
+            super().__init__(name=type(self).__name__, daemon=True)
+
+        @staticmethod
+        def _size():
+            ioctl = fcntl.ioctl(
+                0, termios.TIOCGWINSZ, struct.pack("HHHH", 0, 0, 0, 0)
+            )
+            th, tw, hp, wp = struct.unpack("HHHH", ioctl)
+            return tw, th
+
+        def run(self):
+            last_resize = float("inf")
+            first_print = True
+            self.logger.info("Resizer running")
+            self._run = True
+            while self._run:
+                width = self._size()[0] - 1
+                if width != self.width:
+                    last_resize = time.time()
+                    self.width = width
+                if first_print or last_resize + 0.5 < time.time():
+                    last_resize = float("inf")
+                    pd.set_option("display.width", self.width)
+                    pd.set_option("display.max_rows", self.max_rows)
+                    if first_print:
+                        self.logger.info(
+                            "Resized pandas to %dx%d",
+                            self.width,
+                            self.max_rows,
+                        )
+                        first_print = False
+                time.sleep(0.2)
+
+        def stop(self):
+            self._run = False
+
+    PandasResizer().start()
+
+
+try:
+    import pandas as pd
+    import numpy as np
+except ModuleNotFoundError:
+    pass
+else:
+    _setup()
+
+
+del _setup
+
+_summarise_startup()