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

2024-05-13 19:00:31 发布

您现在位置:Python中文网/ 问答频道 /正文

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

Tags: 代码inpyimportinitlibpackagesusr
2条回答

尝试设置环境变量$DISPLAY

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

你试过调用cronjob中的显示吗?在

Cronjob公司:

* * * * * DISPLAY=:0.0 python /home/username/Documents/file.py

在python代码中,还可以尝试在开始时调用显示:

^{pr2}$

另外,pynotify在根目录下不起作用。所以你应该写你的crontab而不是sudo

crontab -e

相关问题 更多 >