通过crontab运行带有虚拟环境的Python时,plt.show() 无法显示绘图

编程语言 2026-07-09

我有一个Python脚本,test.py:

import matplotlib.pyplot as plt
plt.plot()
plt.show()
plt.savefig("/home/user/Desktop/test.png")

当我用以下方式在虚拟环境中运行它时,

user@mysystem:~$ /home/user/Desktop/dailyreports/env/bin/python3 /home/user/Desktop/dailyreports/test.py

它会显示图形并保存test.png。 一切按预期工作。

但我用crontab来触发这个脚本,使用以下命令,

* * * * * /home/user/Desktop/dailyreports/env/bin/python3 /home/user/Desktop/dailyreports/test.py

它保存了test.png,因此脚本在运行,但不会显示图形。如何让它显示我的图形?

我试过在 plt.show() 中设置 block=True,但没有任何区别。

我使用的是Ubuntu 24.04和 Python 3.12.3

解决方案

What I would do is use xdg-open to open the file. For example:

xdg-open /home/user/Desktop/test.png

如果你需要更多帮助,请告诉我!

站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。

相关文章