我在同时使用这三种技术时遇到了一些困难。
Cron 条目:
* * * * * /usr/bin/python /path/to/python/email/program.py
Python 程序:
1 #!/usr/bin/python
2
3 import imaplib
4 import os
5 import sys
6 import pynotify
7
8 if not pynotify.init('Emails'):
9 sys.exit(1)
10
11 with open('/path/to/python/email/count.tmp', 'r') as file:
12 data = int(file.read().strip())
13 client = imaplib.IMAP4_SSL('mail.sever.com', '993')
14 client.login('user@server.com', 'password')
15 client.select()
16
17 unseen = client.search(None, 'UnSeen')[1][0].split()
18
19 if unseen[0] == '':
20 pass
21 else:
22 if len(unseen) != data:
23 n = pynotify.Notification(str(len(unseen) - data) + " New Messages",
24 str(len(unseen)) + " Unread Messages",
25 "file:///path/to/python/email/mail.png")
26 if not n.show():
27 print "Fail"
28 sys.exit(1)
30 with open('/path/to/python/email/count.tmp', 'w') as file:
31 file.write(str(len(unseen)))
该脚本在单独运行时可以正常工作,但在计划为 cron 作业时不会运行。我检查了系统日志,它说脚本正在运行,我已经以 sudo 身份运行日志中的行以进行验证。
我检查过
Execute python Script on Crontab
和
但似乎都没有解决这种组合,也没有进一步的链接。
有什么想法吗?
-更新1-
由于 pynotify 似乎根本不允许该程序运行,因此我已将它们的调用替换为 os.system 调用。至少这更新了小 tmp 文件,但仍然没有通知。
os.system('/usr/bin/X11/notify-send "{} New Messages" "{} Unread Messages"'.format(len(unseen) - data, len(unseen))
-更新2-
/usr/lib/python2.7/dist-packages/gtk-2.0/gtk/__init__.py:57: GtkWarning: could not open display
warnings.warn(str(e), _gtk.Warning)
** (other.py:16509): WARNING **: Command line `dbus-launch --autolaunch=91bdcc4a583bfb56734fbe1200000010 --binary-syntax --close-stderr' exited with non-zero exit status 1: Autolaunch error: X11 initialization failed.\n
请您参考如下方法:
当您手动运行您的程序时,它可以正常工作,因为变量 DISPLAY正在设置为您当前的显示(在大多数情况下为 :0),但是当通过 cron 运行脚本时,没有设置此类变量并且通知不起作用。
如 this answer 中所述,您应该同时导出显示和 Xauthority,最后以您的用户身份(而不是根用户)运行脚本。
尝试这样的事情:
* * * * * export DISPLAY=:0.0 && export XAUTHORITY=/home/<username>/.Xauthority && sudo -u <username> /usr/bin/python /path/to/python/email/program.py
(将 <username> 更改为您的用户名)
