Python代码在终端中工作,但在cronjob中不工作



我写了一段代码,每当执行时都会通知我。我想每半小时运行一次这段代码,因此创建了一个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()

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

您是否尝试在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

尝试设置环境变量$DISPLAY

* * * * * env DISPLAY=:0 cd /home/username/Documents && /usr/bin/python file.py >> /home/username/Desktop/mylog.log 2>&1

相关内容

最新更新