ReFRACtor
safe_matplotlib_import.py
Go to the documentation of this file.
1 # A direct import of matplotlib will fail if we aren't attached to a X display.
2 # If we can't import using the default gtk toolkit, switch to "agg" which
3 # doesn't require a display.
4 
5 # Use agg if we know we don't have a display.
6 import os, sys
7 if('matplotlib.backends' not in sys.modules and
8  (os.getenv("DISPLAY") is None or
9  os.getenv("DISPLAY") == "")):
10  import matplotlib
11  matplotlib.use('agg')
12 
13 # We still might fail, if for example we have a DISPLAY environment variable
14 # set for a display that isn't there anymore. So go ahead and try to import,
15 # but if this fails then switch to agg.
16 try:
17  import warnings
18  warnings.filterwarnings(action="ignore",
19  message=".*gdk_cursor_new_for_display: assertion `GDK_IS_DISPLAY \\(display\\)' failed.*")
20  warnings.filterwarnings(action="ignore",
21  message=".*could not open display.*")
22  import matplotlib.pyplot as plt
23 except (RuntimeError, ImportError):
24  import matplotlib
25  matplotlib.use('agg', warn=False, force=True)
26  import matplotlib.pyplot as plt
27 finally:
28  # Remove our filters
29  warnings.filters.pop(0)
30  warnings.filters.pop(0)

Copyright © 2017, California Institute of Technology.
ALL RIGHTS RESERVED.
U.S. Government Sponsorship acknowledged.
Generated Fri Aug 24 2018 15:44:10