使用matplotlib自动检测显示的可用性 [英] Automatic detection of display availability with matplotlib

查看:65
本文介绍了使用matplotlib自动检测显示的可用性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在生成脚本中的matplotlib图形,无论是否显示图形,我都可以运行该脚本.我希望脚本自动调整:在显示的情况下,它应该以交互方式显示图形,而在没有显示的情况下,应将它们保存到文件中.

I'm generating matplotlib figures in a script which I run alternatively with or without a graphical display. I'd like the script to adjust automatically: with display, it should show the figures interactively, while without a display, it should just save them into a file.

从问题的答案中在不运行X的情况下生成matplotlib图服务器,我了解到可以使用Agg后端进行非交互式绘图.

From an answer to the question Generating matplotlib graphs without a running X server, I learnt that one can use the Agg backend for non-interactive plotting.

所以我正在尝试这段代码:

So I am trying with this code:

import matplotlib
try:
    import matplotlib.pyplot as plt
    fig = plt.figure()
    havedisplay = True
except:
    matplotlib.use("Agg")
    import matplotlib.pyplot as plt
    fig = plt.figure()
    havedisplay = False
# do the plotting
if havedisplay:
    plt.show()
else:
    fig.savefig("myfig.png")

与带显示器的情况相同.但是,没有显示,由于已经选择了显示,因此对matplotlib.use的调用无效.很明显,我应该在import matplotlib.pyplot之前调用matplotlib.use,但是然后我不知道如何测试显示器是否可用.

This works as excepted in the case with a display. However, without a display, the call to matplotlib.use is not effective, since the display has already been chosen. It's clear that I should call matplotlib.use before import matplotlib.pyplot, but then I don't know how to test whether a display is available or not.

我也尝试使用实验功能matplotlib.switch_backend而不是matplotlib.use,但这会生成RuntimeError.

I have also tried with the experimental function matplotlib.switch_backend instead of matplotlib.use, but this generates a RuntimeError.

有人知道如何使上述代码按预期工作,还是可以建议一种替代方法来检测显示器是否可用于matplotlib?

Does someone have an idea how to make the above code work as intended, or can suggest an alternative way to detect whether a display is available for matplotlib or not?

推荐答案

您可以直接检测是否使用python的OS模块进行显示. 在我的情况下是

You can detect directly if you have a display with the OS module in python. in my case it's

>>> import os
>>> os.environ["DISPLAY"]
':0.0'

这篇关于使用matplotlib自动检测显示的可用性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆