我有一个使用matplotlib编写的模块。但是,我需要它与显示器(例如命令行执行)一起工作,或者当没有显示时(SGE / qsub群集作业或cron作业)。
我找到了这个答案(Automatic detection of display availability with matplotlib),它适用于命令行执行和集群作业。但是,在一个cron作业中,它无法正确导入matplotlib,并且在导入之前似乎抛出异常。
在cronjob中,我尝试使用以下脚本导入我的模块:
import os
os.environ['PYTHONPATH'] = 'path/to/my/module/dir:%s' % os.environ['PYTHONPATH']
print 'now loading mymodule...'
import mymodule
和mymodule.py只包含早期链接答案中的代码:
#!/usr/bin/python
import os
print 'testing import method...'
import matplotlib
r = 0
try :
r = os.system('python -c "import matplotlib.pyplot as plt;plt.figure()"')
except RuntimeError :
pass
print 'r=%d' % r
if r != 0:
print 'matplotlib: running in cluster, using Agg!'
matplotlib.use('Agg')
import matplotlib.pyplot as plt
我从cron服务收到此错误消息:
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "/afs/ifh.de/user/u/user/.local/lib/python2.6/site-packages/matplotlib/pyplot.py", line 109, in <module>
_backend_mod, new_figure_manager, draw_if_interactive, _show = pylab_setup()
File "/afs/ifh.de/user/u/user/.local/lib/python2.6/site-packages/matplotlib/backends/__init__.py", line 32, in pylab_setup
globals(),locals(),[backend_name],0)
File "/afs/ifh.de/user/u/user/.local/lib/python2.6/site-packages/matplotlib/backends/backend_gtkagg.py", line 14, in <module>
from matplotlib.backends.backend_gtk import gtk, FigureManagerGTK, FigureCanvasGTK,\
File "/afs/ifh.de/user/u/user/.local/lib/python2.6/site-packages/matplotlib/backends/backend_gtk.py", line 16, in <module>
import gtk; gdk = gtk.gdk
File "/usr/lib64/python2.6/site-packages/gtk-2.0/gtk/__init__.py", line 64, in <module>
_init()
File "/usr/lib64/python2.6/site-packages/gtk-2.0/gtk/__init__.py", line 52, in _init
_gtk.init_check()
RuntimeError: could not open display
now loading mymodule...
testing import method...
r=256
matplotlib: running in cluster, using Agg!
我认为它尝试并且无法导入matplotlib,它会在到mymodule.py中的代码之前抛出一个RuntimeError 。我可以看到它到达我的代码并运行它,但Traceback消息让我感到紧张。
为什么在我告诉它(使用Agg)之前加载matplotlib(和崩溃)?如何修复/隐藏该回溯消息?
答案 0 :(得分:0)
作为隐藏回溯消息的肮脏技巧,只需将cronjob中的所有错误传递给/dev/null
:
script.py 2> /dev/null