summarylogtreecommitdiffstats
path: root/python-matplotlib-pickled-figure-opener
blob: ce624e15153d88ca3261a7709018e78279a81dcd (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
#!/usr/bin/python
import pickle
import argparse
import importlib
import logging
import sys
import itertools
import fnmatch
import zstandard

parser = argparse.ArgumentParser(description="Show a pickled (and possibly compressed) Matplotlib figure" )
parser.add_argument("filename",help="the file to open")
args = parser.parse_args()

openers = {}

for module_name,patterns in {
    "lzma": ("*.xz","*.lzma"),
    "bz2": ("*.bz2", "*.bzip2"),
    "gzip": ("*.gz", "*.gzip"),
    "zstandard": ("*.zst", "*.zstd"),
}.items():
    try:
        module = importlib.import_module(module_name)
        try:
            openers[patterns] = getattr(module,"open")
        except AttributeError:
            logging.warning(f"Module '{module_name}' does not have an 'open' function. Ignoring it.")
    except ImportError:
        logging.warning(f"No such module '{module_name}'. Ignoring it.")

import matplotlib.pyplot as plt

for patterns, opener in itertools.chain(openers.items(),{("*",):open}.items()):
    if not any(fnmatch.fnmatch(args.filename,pattern) for pattern in patterns):
        continue
    try:
        while True:
            reload = False
            with opener(args.filename, "rb") as fh:
                try:
                    fig = pickle.load(fh)
                except pickle.UnpicklingError as e:
                    logging.error(f"{type(e).__name__}: {e}")
                    break

            def on_key(event):
                global reload
                if event.key == "r":
                    print('reloading!')
                    plt.close("all")
                    reload = True

            cid = fig.canvas.mpl_connect('key_press_event', on_key)
            plt.show()
            if not reload:
                sys.exit(0)

    except (ValueError,TypeError) as e:
        logging.error(f"{type(e).__name__}: {e}")
        continue