我已经编写了一个代码,无论何时执行它都会通知我。我想在每半个小时后运行这段代码,因此创建了一个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:
* * * * * cd /home/username/Documents && /usr/bin/python file.py >> /home/username/Desktop/mylog.log 2>&1
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()
cronjob记录了notify2脚本:
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
答案 0 :(得分:2)
您是否尝试在cronjob中调用显示器?
的cronjob:
* * * * * DISPLAY=:0.0 python /home/username/Documents/file.py
在你的python代码中,你也可以尝试在开头调用Display:
import os
# environnement vars
os.environ.setdefault('XAUTHORITY', '/home/user/.Xauthority')
os.environ.setdefault('DISPLAY', ':0.0')
此外,pynotify在root中不起作用。所以你应该在没有“sudo”的情况下编写你的crontab
crontab -e
答案 1 :(得分:0)
尝试设置环境变量$ DISPLAY
* * * * * env DISPLAY=:0 cd /home/username/Documents && /usr/bin/python file.py >> /home/username/Desktop/mylog.log 2>&1