Automatic detection of display availability with matplotlib

后端 未结 7 1653
悲&欢浪女
悲&欢浪女 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 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).

提交回复
热议问题