Skip to main content
 首页 » 编程设计

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

2024年10月25日11zhwl

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

定时任务:

* * * * * cd /home/username/Documents && /usr/bin/python file.py >> /home/username/Desktop/mylog.log 2>&1 

定时任务日志:

/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 中调用显示?

定时任务:

* * * * * 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