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

Skip to content

Backport PR #18245 on branch v3.3.x #18253

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 17 additions & 1 deletion lib/matplotlib/pyplot.py
Original file line number Diff line number Diff line change
Expand Up @@ -232,10 +232,26 @@ def switch_backend(newbackend):
close("all")

if newbackend is rcsetup._auto_backend_sentinel:
current_framework = cbook._get_running_interactive_framework()
mapping = {'qt5': 'qt5agg',
'qt4': 'qt4agg',
'gtk3': 'gtk3agg',
'wx': 'wxagg',
'tk': 'tkagg',
'macosx': 'macosx',
'headless': 'agg'}

best_guess = mapping.get(current_framework, None)
if best_guess is not None:
candidates = [best_guess]
else:
candidates = []
candidates += ["macosx", "qt5agg", "gtk3agg", "tkagg", "wxagg"]

# Don't try to fallback on the cairo-based backends as they each have
# an additional dependency (pycairo) over the agg-based backend, and
# are of worse quality.
for candidate in ["macosx", "qt5agg", "gtk3agg", "tkagg", "wxagg"]:
for candidate in candidates:
try:
switch_backend(candidate)
except ImportError:
Expand Down
34 changes: 34 additions & 0 deletions lib/matplotlib/tests/test_backends_interactive.py
Original file line number Diff line number Diff line change
Expand Up @@ -191,3 +191,37 @@ def test_webagg():
conn.close()
proc.send_signal(signal.SIGINT)
assert proc.wait(timeout=_test_timeout) == 0


@pytest.mark.skipif(sys.platform != "linux", reason="this a linux-only test")
@pytest.mark.backend('Qt5Agg', skip_on_importerror=True)
def test_lazy_linux_headless():
test_script = """
import os
import sys

# make it look headless
del os.environ['DISPLAY']

# we should fast-track to Agg
import matplotlib.pyplot as plt
plt.get_backend() == 'agg'
assert 'PyQt5' not in sys.modules

# make sure we really have pyqt installed
import PyQt5
assert 'PyQt5' in sys.modules

# try to switch and make sure we fail with ImportError
try:
plt.switch_backend('qt5agg')
except ImportError:
...
else:
sys.exit(1)

"""
proc = subprocess.run([sys.executable, "-c", test_script])
if proc.returncode:
pytest.fail("The subprocess returned with non-zero exit status "
f"{proc.returncode}.")