我写了一个代码,在执行时会通知我。我想每半小时运行一次这个代码,因此创建了一个cronjob。但是当通过cronjob执行时,代码不起作用。在
我的代码是:
import sys
import pynotify
if __name__ == "__main__":
if not pynotify.init("icon-summary-body"):
sys.exit(1)
n = pynotify.Notification("Subject","Message","notification-message-im")
n.show() #throws error here
Cronjob公司:
^{pr2}$Cronjob日志:
/usr/lib/python2.7/dist-packages/gtk-2.0/gtk/__init__.py:57: GtkWarning: could not open display
warnings.warn(str(e), _gtk.Warning)
Traceback (most recent call last):
File "file.py", line 8, in <module>
n.show()
gio.Error: Cannot autolaunch D-Bus without X11 $DISPLAY
可能是什么原因造成的呢?在
我也尝试使用notify2
,但没有成功。可以正常执行,但不能通过cronjob
这是notify2代码:
import notify2
notify2.init('app name')
n = notify2.Notification("Summary","Some body text","notification-message-im")
n.show()
notify2脚本的Cronjob日志:
Traceback (most recent call last):
File "file.py", line 3, in <module>
notify2.init('app name')
File "/usr/local/lib/python2.7/dist-packages/notify2.py", line 93, in init
bus = dbus.SessionBus(mainloop=mainloop)
File "/usr/lib/python2.7/dist-packages/dbus/_dbus.py", line 211, in __new__
mainloop=mainloop)
File "/usr/lib/python2.7/dist-packages/dbus/_dbus.py", line 100, in __new__
bus = BusConnection.__new__(subclass, bus_type, mainloop=mainloop)
File "/usr/lib/python2.7/dist-packages/dbus/bus.py", line 122, in __new__
bus = cls._new_for_bus(address_or_type, mainloop=mainloop)
dbus.exceptions.DBusException: org.freedesktop.DBus.Error.NotSupported: Unable to autolaunch a dbus-daemon without a $DISPLAY for X11
如何通过cronjob运行此代码?在
编辑
代码如下:
import sys
import pynotify
import os
os.environ.setdefault('XAUTHORITY', '/home/user/.Xauthority')
os.environ.setdefault('DISPLAY', ':0.0')
if __name__ == "__main__":
if not pynotify.init("icon-summary-body"):
sys.exit(1)
n = pynotify.Notification("Subject","Message","notification-message-im")
n.show() #throws error here
我现在得到:
/usr/lib/python2.7/dist-packages/gtk-2.0/gtk/__init__.py:57: GtkWarning: could not open display
warnings.warn(str(e), _gtk.Warning)
Traceback (most recent call last):
File "file.py", line 12, in <module>
n.show() #throws error here
gio.Error: Could not connect: Connection refused
尝试设置环境变量$DISPLAY
你试过调用cronjob中的显示吗?在
Cronjob公司:
在python代码中,还可以尝试在开始时调用显示:
^{pr2}$另外,pynotify在根目录下不起作用。所以你应该写你的crontab而不是sudo
相关问题 更多 >
编程相关推荐