Automatic detection of display availability with matplotlib

后端 未结 7 1617
悲&欢浪女
悲&欢浪女 2020-12-15 06:26

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

相关标签:
7条回答
  • 2020-12-15 06:52

    The code below works for me in Linux and Windows (where it assumes there is a display device):

    import os
    import matplotlib
    if os.name == 'posix' and "DISPLAY" not in os.environ:
        matplotlib.use('Agg')
    

    See https://stackoverflow.com/a/1325587/896111.

    Note that the line matplotlib.use('Agg') must appear after the first import of matplotlib (otherwise you will get an error).

    0 讨论(0)
  • 2020-12-15 06:53

    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'
    
    0 讨论(0)
  • 2020-12-15 06:53

    when use GUI backend the figure object has show() method, you can use it to do the switch:

    import matplotlib
    #matplotlib.use("Agg")
    
    import matplotlib.pyplot as plt
    fig = plt.figure()
    havedisplay = False
    if hasattr(fig, "show"):
        plt.show()
    else:
        print "save fig"
        fig.savefig("myfig.png")
    
    0 讨论(0)
  • 2020-12-15 06:54

    try this?

    import matplotlib,os
    r = os.system('python -c "import matplotlib.pyplot as plt;plt.figure()"')
    if r != 0:
        matplotlib.use('Agg')
        import matplotlib.pyplot as plt
        fig = plt.figure()
        fig.savefig('myfig.png')
    else:
        import matplotlib.pyplot as plt
        fig = plt.figure()
        plt.show()
    
    0 讨论(0)
  • 2020-12-15 07:00

    The solution offered by @Oz123 generated a syntax error for me. However, i was able to easily detect the display using:

    import os
    havedisplay = "DISPLAY" in os.environ
    #plotting...
    

    That was the simplest thing i could find, anyway.

    0 讨论(0)
  • 2020-12-15 07:10

    By combining both of the approaches above, you'll get perhaps the best solution:

    havedisplay = "DISPLAY" in os.environ
    if not havedisplay:
        exitval = os.system('python -c "import matplotlib.pyplot as plt; plt.figure()"')
        havedisplay = (exitval == 0)
    

    The reason for this combo is that the run time of the os.system command may take a while. So when you are sure you have the display (judging by the os.environ value), you can save that time. On the other hand, even if the DISPLAY key is not set in the os.environ variable, there is still a chance that the plotting methods will work with the graphical interface (e.g. when using Windows command line).

    0 讨论(0)
提交回复
热议问题