Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 6c1e8e0

Browse files
authored
Merge pull request #18253 from jkseppan/auto-backport-of-pr-18245-on-v3.3.x
Backport PR #18245 on branch v3.3.x
2 parents e49322d + 0fb2d0b commit 6c1e8e0

File tree

2 files changed

+51
-1
lines changed

2 files changed

+51
-1
lines changed

lib/matplotlib/pyplot.py

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -232,10 +232,26 @@ def switch_backend(newbackend):
232232
close("all")
233233

234234
if newbackend is rcsetup._auto_backend_sentinel:
235+
current_framework = cbook._get_running_interactive_framework()
236+
mapping = {'qt5': 'qt5agg',
237+
'qt4': 'qt4agg',
238+
'gtk3': 'gtk3agg',
239+
'wx': 'wxagg',
240+
'tk': 'tkagg',
241+
'macosx': 'macosx',
242+
'headless': 'agg'}
243+
244+
best_guess = mapping.get(current_framework, None)
245+
if best_guess is not None:
246+
candidates = [best_guess]
247+
else:
248+
candidates = []
249+
candidates += ["macosx", "qt5agg", "gtk3agg", "tkagg", "wxagg"]
250+
235251
# Don't try to fallback on the cairo-based backends as they each have
236252
# an additional dependency (pycairo) over the agg-based backend, and
237253
# are of worse quality.
238-
for candidate in ["macosx", "qt5agg", "gtk3agg", "tkagg", "wxagg"]:
254+
for candidate in candidates:
239255
try:
240256
switch_backend(candidate)
241257
except ImportError:

lib/matplotlib/tests/test_backends_interactive.py

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -191,3 +191,37 @@ def test_webagg():
191191
conn.close()
192192
proc.send_signal(signal.SIGINT)
193193
assert proc.wait(timeout=_test_timeout) == 0
194+
195+
196+
@pytest.mark.skipif(sys.platform != "linux", reason="this a linux-only test")
197+
@pytest.mark.backend('Qt5Agg', skip_on_importerror=True)
198+
def test_lazy_linux_headless():
199+
test_script = """
200+
import os
201+
import sys
202+
203+
# make it look headless
204+
del os.environ['DISPLAY']
205+
206+
# we should fast-track to Agg
207+
import matplotlib.pyplot as plt
208+
plt.get_backend() == 'agg'
209+
assert 'PyQt5' not in sys.modules
210+
211+
# make sure we really have pyqt installed
212+
import PyQt5
213+
assert 'PyQt5' in sys.modules
214+
215+
# try to switch and make sure we fail with ImportError
216+
try:
217+
plt.switch_backend('qt5agg')
218+
except ImportError:
219+
...
220+
else:
221+
sys.exit(1)
222+
223+
"""
224+
proc = subprocess.run([sys.executable, "-c", test_script])
225+
if proc.returncode:
226+
pytest.fail("The subprocess returned with non-zero exit status "
227+
f"{proc.returncode}.")

0 commit comments

Comments
 (0)