summary refs log tree commit diff
path: root/dot_ipython/profile_default/startup/80_pandas.py
blob: be1886948adf72d519b4e1eac5f3420297667e0d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
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()