数码资讯
crontab 中 python 脚本执行失败的解决方法
写服务器程序的免不了要经常和 crontab 打交道,定时执行一些脚本什么的。大部分情况下都是 bash 的一些 shell 脚本,但 shell 我不是很熟悉,于是在很多情况下都直接写 Python 脚本来搞定它。今天写了一个操作 PostgreSQL 数据库的 Python 脚本,放到 cron
写服务器程序的免不了要经常和 crontab 打交道,定时执行一些脚本什么的。大部分情况下都是 bash 的一些 shell 脚本,但 shell 我不是很熟悉,于是在很多情况下都直接写 Python 脚本来搞定它。今天写了一个操作 PostgreSQL 数据库的 Python 脚本,放到 crontab 中定时执行的时候,时间到了却没有任何反映。但是如果在命令行下直接执行的话,没有任何问题。
动态展示日志的命令:
# tail -f /var/log/cron
首先看看 crontab 的日志(/var/log/cron),日志中显示脚本定时执行了。那么一定是在 crontab 运行该脚本的时候报错。直接在 Python 脚本中从第一行开始写一个大大的 try 模块,显示一下 Exception 的内容。果然,抓到了…… 错误日志显示显示 Python 找不到 libpq.so.5 这个 PostgreSQL 的库。
原来 crontab 的运行环境和我们用 root 登录进去的环境都是不同的,需要在运行 Python 脚本前重新设定一下运行的环境变量如 LD_LIBRARY_PATH。这下比较好办了,直接写一个 shell 脚本,设置一下环境变量,再调用 Python 吧。 libpq.so.5 这个库我是装在 /usr/local/pgsql/lib 中。最后的脚本如下:
搞定,crontab 又跑得欢快起来了。
折腾了一个上午,写下来备忘。
本地测试:
要执行的python脚本:
config.py
''' Created on Sep 14, 2012 @author: dashan.yin ''' smtpserver='smtp.domainname.com' smtpuser='xxx@domainname.com' smtppass='pwd' smtpport='25'
sendmail.py
#!usr/bin/env python
#coding: utf-8
import smtplib, config, email, sys
from email.Message import Message
def connect():
"connect to smtp server and return a smtplib.SMTP instance object"
try:
server = smtplib.SMTP(config.smtpserver, config.smtpport)
server.ehlo()
server.login(config.smtpuser, config.smtppass)
except Exception:
print Exception
print 'Error - connect failed'
else:
print "connect success!"
return server
def sendmessage(server, to, subj, content):
"using server send a email"
msg = Message()
msg['Mime-Version'] = '1.0'
msg['From'] = config.smtpuser
msg['To'] = to
msg['Subject'] = subj
msg['Date'] = email.Utils.formatdate() # curr datetime, rfc2822
msg.set_payload(content)
try:
failed = server.sendmail(config.smtpuser, to, str(msg)) # may also raise exc
except Exception , ex:
print Exception, ex
print 'Error - send failed'
else:
print "send success!"
if __name__ == "__main__":
to = "dashan.yin@domainname.com"
subj = "test"
text = u"测试python发送邮件程序"
server = connect()
sendmessage(server, to, subj, text)
shell脚本:
sendmail.sh
#!/bin/sh /usr/local/bin/python /usr/local/sbin/sendmail.py
定时设置:
crontab -u root -e */1 * * * * sh /usr/local/sbin/sendmail.sh
然后这样就可以定时发邮件了。根据设置是每分钟发一封!
常见的问题:
1.sendmail.sh sendmail.py是否有可执行权限,如果没有的话执行下面命令:
chmod +x sendmail.sh/sendmail.py
2.sendmail.sh sendmail.py都要使用绝对路径。(这一点一定要注意,搞了一下午就栽在这上了)