It is a small story. It's a rare case, but it's a solution when Python requires you to execute a function or method before importing.
When I installed matplotlib on Linux and used it on my Python code, I got the following error:
_tkinter.TclError: no display name and no $DISPLAY environment variable
The solution to this error comes up as soon as I search, and the answer seems to be that matplotlib's backend should be Agg. (Details about errors and backends are omitted this time)
There seem to be several ways to do this, and the method of writing backend: Agg
in / etc / matplotlibrc [^ 1] and the method of usingmatplotlib.use ('Agg')
[^ 2] are the top searches. It was up to.
This time, let's assume that we will use matplotlib.use ('Agg')
.
import matplotlib
matplotlib.use('Agg')
from matplotlib import pyplot
def plot(data):
pyplot.plot(data)
If you call matplotlibu.use ('Agg')
after importing as above, it works, but there is a problem with this, a tool that automatically changes the import order ([isort](https: //) pypi.python.org/pypi/isort) etc.) will be rewritten as follows.
import matplotlib
from matplotlib import pyplot
matplotlib.use('Agg')
def plot(data):
pyplot.plot(data)
It seems that matplotlib.use ('Agg')
must be called before writing from matplotlib import pyplot
, which can be a problem if CI automatically checks the code. There is a way to import it in the calling function at runtime, but it becomes more complicated as the number of imports and the number of functions increases.
As a countermeasure, it can be implemented as follows.
try:
import matplotlib
matplotlib.use('Agg')
finally:
from matplotlib import pyplot
def plot(data):
pyplot.plot(data)
For the time being, this can guarantee the order.
[^ 1]: How to prevent recurrence of matplotlib moss problem with undefined $ DISPLAY
[^ 2]: Draw a graph with matplotlib.
Recommended Posts