简体   繁体   English

使用crontab运行时,matplotlib savefig不起作用

[英]matplotlib savefig doesn't work when run with crontab

I'm trying to run a python script with crontab that uses matplotlib to save a plot png. 我正在尝试使用crontab运行python脚本,该脚本使用matplotlib保存图png。 The script runs fine when run normally/not by cron. 正常/不由cron运行时,脚本运行良好。

My crontab file is: 我的crontab文件是:

SHELL=/bin/bash
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
* * * * * /home/matthew/Programs/random_walk/random_walk.py >/dev/null 2>&1

Permissions seem to be set correctly and pythonpath seems right; 权限似乎设置正确,而pythonpath似乎正确; I added a couple lines to random_walk.py that write a file with the sys.path output, and that worked when run by cron. 我在random_walk.py中添加了几行,用sys.path输出写入一个文件,并且在由cron运行时有效。

Several blog posts and mailing lists suggested the problem would be resolved by having 一些博客文章和邮件列表建议通过以下方式解决该问题:

import matplotlib
matplotlib.use('Agg')

at the top of my python file (after the shebang), but that doesn't help. 在我的python文件的顶部(在shebang之后),但这没有帮助。

My savefig code is 我的savefig代码是

if len(sys.argv) > 1:
    save_path = sys.argv[1].rstrip('/')+'/random_walk.png'
else:
    save_path = 'random_walk.png'
plt.savefig(save_path)

How can I get cron and matplotlib to play nicely together? 我怎样才能使cron和matplotlib一起很好地玩?

Thanks to @tcaswell, I figured out that the problem was a paths issue. 感谢@tcaswell,我发现问题是路径问题。

My crontab file was not passing the image file location to random_walk.py, so the image was being saved in the same directory as my crontab file- not the same directory as random_walk.py where I was expecting it. 我的crontab文件没有将图像文件的位置传递给random_walk.py,因此图像与我的crontab文件保存在同一目录中,而不是我期望的与random_walk.py所在的目录。

Solution 1 解决方案1

Pass the path to the script in crontab like I meant to. 像我本意那样将路径传递到crontab中的脚本。

SHELL=/bin/bash
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
* * * * * /home/matthew/Programs/random_walk/random_walk.py /home/matthew/Programs/random_walk >/dev/null 2>&1

Solution 2 解决方案2

Alternatively, I could just make the python script always write its output file where I want it to go. 或者,我可以使python脚本始终将其输出文件写入我想要的位置。 In this case, I want the output file to be in the same directory as the random_walk.py, so I'm using the following code: 在这种情况下,我希望输出文件与random_walk.py位于同一目录中,因此我使用以下代码:

save_path = ''
if len(sys.argv) > 1:
    save_path = sys.argv[1].rstrip('/')+'/random_walk.png'
else:
    save_path = os.path.dirname(os.path.realpath(__file__))+'/random_walk.png'
plt.savefig(save_path)

Note 注意

Just to be clear, having 只是要清楚,

import matplotlib
matplotlib.use('Agg')

was also necessary to get matplotlib to work with cron. 使matplotlib与cron一起使用也是必需的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM