[Python] RuntimeError: Invalid DISPLAY variable

1.问题:在本地用matplotlib绘图可以,但是在ssh远程绘图的时候会报错 RuntimeError: Invalid DISPLAY variable

2.原因:matplotlib的默认backend是TkAgg,而FltkAgg, GTK, GTKAgg, GTKCairo, TkAgg , Wx or WxAgg这几个backend都要求有GUI图形界面的,所以在ssh操作的时候会报错.

import matplotlib.pyplot as plt
Backend TkAgg is interactive backend. Turning interactive mode on.

plt.get_backend()
Out[3]: u‘TkAgg‘

3.解决方法:指定不需要GUI的backend(Agg, Cairo, PS, PDF or SVG

import matplotlib.pyplot as plt
plt.switch_backend(‘agg‘)

4.源码

查看plt.switch_backend()的源码实现和解析:

def switch_backend(newbackend):
    """
    Switch the default backend.  This feature is **experimental**, and
    is only expected to work switching to an image backend.  e.g., if
    you have a bunch of PostScript scripts that you want to run from
    an interactive ipython session, you may want to switch to the PS
    backend before running them to avoid having a bunch of GUI windows
    popup.  If you try to interactively switch from one GUI backend to
    another, you will explode.

    Calling this command will close all open windows.
    """
    close(‘all‘)
    global _backend_mod, new_figure_manager, draw_if_interactive, _show
    matplotlib.use(newbackend, warn=False, force=True)
    from matplotlib.backends import pylab_setup
    _backend_mod, new_figure_manager, draw_if_interactive, _show = pylab_setup()

查看matplotlib.use()的源码:

def use(arg, warn=True, force=False):
    """
    Set the matplotlib backend to one of the known backends.

    The argument is case-insensitive. *warn* specifies whether a
    warning should be issued if a backend has already been set up.
    *force* is an **experimental** flag that tells matplotlib to
    attempt to initialize a new backend by reloading the backend
    module.

    .. note::

        This function must be called *before* importing pyplot for
        the first time; or, if you are not using pyplot, it must be called
        before importing matplotlib.backends.  If warn is True, a warning
        is issued if you try and call this after pylab or pyplot have been
        loaded.  In certain black magic use cases, e.g.
        :func:`pyplot.switch_backend`, we are doing the reloading necessary to
        make the backend switch work (in some cases, e.g., pure image
        backends) so one can set warn=False to suppress the warnings.

    To find out which backend is currently set, see
    :func:`matplotlib.get_backend`.

    """
    # Lets determine the proper backend name first
    if arg.startswith(‘module://‘):
        name = arg
    else:
        # Lowercase only non-module backend names (modules are case-sensitive)
        arg = arg.lower()
        name = validate_backend(arg)

    # Check if we‘ve already set up a backend
    if ‘matplotlib.backends‘ in sys.modules:
        # Warn only if called with a different name
        if (rcParams[‘backend‘] != name) and warn:
            warnings.warn(_use_error_msg)

        # Unless we‘ve been told to force it, just return
        if not force:
            return
        need_reload = True
    else:
        need_reload = False

    # Store the backend name
    rcParams[‘backend‘] = name

    # If needed we reload here because a lot of setup code is triggered on
    # module import. See backends/__init__.py for more detail.
    if need_reload:
        reload(sys.modules[‘matplotlib.backends‘])

参考:DISPLAY error matplotlib http://chewpichai.blogspot.com/2008/01/display-error-matplotlib.html 。原文可能被墙了,需要设法翻一下。

原文内容:

DISPLAY error matplotlib
When error occur about this "$DISPLAY not set" when you run python code that use matplotlib this happened because your matplotlib backend is set to FltkAgg, GTK, GTKAgg, GTKCairo, TkAgg , Wx or WxAgg they required a GUI that why error occur.

To solve this you must specific other backend that not required GUI (Agg, Cairo, PS, PDF or SVG) when use matplotlib like this
In code
 import matplotlib
 matplotlib.use(‘Agg‘)
In command line use -d option
python subplot_demo.py -dAgg

Remember when call savefig(‘filename‘) don‘t give it extension this will handle by backend that you specific e.g Agg will create file filename.png
时间: 2024-11-02 14:03:03

[Python] RuntimeError: Invalid DISPLAY variable的相关文章

RuntimeError: invalid argument 0: Sizes of tensors must match except in dimension 1 #805

具体错误日志如下: The resulting error log is as follows Traceback (most recent call last): File "train.py", line 441, in <module> train() # train normally File "train.py", line 324, in train dataloader=testloader) File "F:\train\yol

python错误 invalid command &#39;bdist_wheel&#39; &amp; outside environment /usr

按照网上说的执行以下命令 sudo pip install --upgrade setuptools sudo pip install --upgrade pip 结果 Not uninstalling setuptools at /usr/lib/python2.7/dist-packages, outside environment /usr 虽然有下载但更新并不成功应该跟python2/3环境有关执行以下命令 sudo apt-get install python3-pip 解决问题 参考

【python】UnboundLocalError: local variable &#39;counter&#39; referenced before assignment

http://passport.baidu.com/?business&un=%E4%BA%91%E9%BE%99%E5%8E%BF%5F%E5%B0%8F%E5%A7%90%5F%E6%89%BE#0 http://passport.baidu.com/?business&un=%E6%89%BE%5F%E6%B4%B1%E6%BA%90%E5%8E%BF%5F%E7%BE%8E%E5%A5%B3#0 http://passport.baidu.com/?business&un=

oracle安装之check if the DISPLAY variable is set错误

原创作品,出自 "深蓝的blog" 博客,欢迎转载,转载时请务必注明以下出处,否则追究版权法律责任. 深蓝的blog:http://blog.csdn.net/huangyanlong/article/details/45021771 linux7下安装oracle12c不弹出图形界面 报错:check if the DISPLAY variable is set. 从上面的内容中,锁定到下面这条错误信息,如下红框标出: 重复尝试几次指令,如下: xhost + DISPLAY=10.

python 错误--UnboundLocalError: local variable &#39;**&#39; referenced before assignment

昨日想在python的一个函数中做一下发送次数的统计,需要用到全局变量,如下 1 COUNT = 0 2 3 def sendOneLineMsg(producer, listFromLine): 4 acSNStr = listFromLine[0] 5 macStr = listFromLine[1] 6 onlineTimeStr = listFromLine[2] 7 msg = {'clientMAC' : macStr, 'acSN' : acSNStr, 'onLineTime'

python IOError: invalid mode (&#39;r&#39;) or filename

我想要用pandas.read_table()将数据表中的数据读到一个pandas DataFrame对象中: import pandas as pd unames = ['user_id', 'gender', 'age', 'occupation', 'zip'] users = pd.read_table('C:\1M data\ml-1m\users.dat', sep='::', header = None, names = unames) 但是报错:invalid mode ('r'

Can&#39;t connect to X11 window server using &#39;:1.0&#39; as the value of the DISPLAY variable.

安装oracle数据时需要用到图形界面安装,当我们用root用户登录后切换到oracle用户时运行./runInstaller提示报错: Can't connect to X11 window server using ':1.0' as the value of the DISPLAY variable. 这是因为没有赋予oracle运行图形界面的权限,这时只要在root下运行xhost + 然后回车即可解决问题.[[email protected] ~]# xhost +access con

CentOS8安装pycharm报错【Can&#39;t connect to X11 window server using &#39;:0&#39; as the value of the DISPLAY variable. 】

在CentOS8 安装pycharm报出如下错误,原来是自己画蛇添足的用sudo执行pycharm.sh,没有按照Install说明里边的直接执行 ./pycharm.sh. 原因见这里:https://www.cnblogs.com/qingqing74647464/p/8685837.html OpenJDK 64-Bit Server VM warning: Option UseConcMarkSweepGC was deprecated in version 9.0 and will l

Linux下运行Java项目时,出现No X11 DISPLAY variable was set, but this program performed an operation which requires it.的问题解决

在~/.bashrc环境变量文件最下方加入: export DISPLAY=:0.0 然后,刷新环境变量以使其生效: source -/.bashrc 参考:http://stackoverflow.com/questions/662421/no-x11-display-variable-what-does-it-mean