通过cron运行的Python脚本偶尔不执行

2 投票
2 回答
1128 浏览
提问于 2025-04-15 22:24

我有一个简单的Python脚本,用来获取推文并把它们缓存到磁盘上,这个脚本设置为每两分钟通过cron自动运行一次。

*/2 * * * * (date ; /usr/bin/python /path/get_tweets.py) >> /path/log/get_tweets.log 2>&1

这个脚本大部分时间都能顺利运行。不过,有时候它会不执行。除了其他的日志记录,我在脚本的主要部分之前加了一个简单的打印语句,但日志中除了最开始的日期命令的输出,什么都没有显示。

#!/usr/bin/python
# Script for Fetching Tweets and then storing them as an HTML snippet for inclusion using SSI

print "Starting get_tweets.py"

import simplejson as json
import urllib2
import httplib
import re
import calendar
import codecs
import os
import rfc822
from datetime import datetime
import time
import sys
import pprint


debug = True 

now = datetime.today()
template = u'<p class="tweet">%s <span class="date">on %s</span></p>'
html_snippet = u''
timelineUrl = 'http://api.twitter.com/1/statuses/user_timeline.json?screen_name=gcorne&count=7'
tweetFilePath = '/path/server-generated-includes/tweets.html'
if(debug): print "[%s] Fetching tweets from %s." % (now, timelineUrl)

def getTweets():
    request = urllib2.Request(timelineUrl)
    opener = urllib2.build_opener()
    try:
        tweets = opener.open(request)
    except:
        print "[%s] HTTP Request %s failed." % (now, timelineUrl)
        exitScript()
    tweets = tweets.read()
    return tweets

def exitScript():
    print "[%s] Script failed." % (now)
    sys.exit(0)


tweets = getTweets()
now = datetime.today()
if(debug): print "[%s] Tweets retrieved." % (now)
tweets = json.loads(tweets)

for tweet in tweets:
    text = tweet['text'] + ' '
    when = tweet['created_at']
    when = re.match(r'(\w+\s){3}', when).group(0).rstrip()
    # print GetRelativeCreatedAt(when)
    # convert links
    text = re.sub(r'(http://.*?)\s', r'<a href="\1">\1</a>', text).rstrip()
    #convert hashtags
    text = re.sub(r'#(\w+)', r'<a href="http://www.twitter.com/search/?q=%23\1">#\1</a>', text)
    # convert @ replies
    text = re.sub(r'@(\w+)', r'@<a href="http://www.twitter.com/\1">\1</a>', text)
    html_snippet += template % (text, when) + "\n"

#print html_snippet

now = datetime.today()
if(debug): print "[%s] Opening file %s." % (now, tweetFilePath)
try:
    file = codecs.open(tweetFilePath, 'w', 'utf_8')
except:
    print "[%s] File %s cound not be opened." % (now, tweetFilePath)
    exitScript()

now = datetime.today()
if(debug): print "[%s] Writing %s to disk." % (now, tweetFilePath)
file.write(html_snippet)

now = datetime.today()
if(debug): print "[%s] Finished writing %s to disk." % (now, tweetFilePath)
file.close()
sys.exit(0)

有没有什么想法?这个系统是一个运行Centos 5.3的VPS,使用的是Python 2.4。

更新:我已经把整个脚本添加上来,以避免任何混淆。

2 个回答

1

我最近遇到了一个问题,使用Python写的脚本有时候在定时任务(crontab)中不运行,但在命令行中总是能正常运行。后来发现,我需要把日志输出重定向到/dev/null。否则,标准输出会满了,程序就会停止,进程也会被杀掉。使用/dev/null来处理输出后,一切就正常了。

2

最可能的原因是,有时候这个脚本运行超过了两分钟(可能是系统偶尔很忙,或者脚本需要等外部网站的响应,而那个网站也偶尔很忙等等)。你的定时任务设置得很合理,会跳过那些还没有完成的重复事件。通过记录脚本的开始和结束时间,你可以确认是不是这种情况。在这种情况下,你可以根据自己的需要来决定怎么做(我建议你考虑跳过偶尔的一次运行,以避免让已经很忙的系统负担更重——无论是你自己的系统,还是你从中获取数据的远程系统)。

撰写回答