3
我有一個不斷從Twitter獲取數據並將消息寫入文件的python腳本。我的問題是每隔一小時,我想讓我的程序將當前時間寫入文件。以下是我的腳本。目前,它進入時間戳功能,並且每10秒鐘就打印一次。在Python中每小時寫入一個文件的時間戳
#! /usr/bin/env python
import tweetstream
import simplejson
import urllib
import time
import datetime
import sched
class twit:
def __init__(self,uname,pswd,filepath):
self.uname=uname
self.password=pswd
self.filepath=open(filepath,"wb")
def main(self):
i=0
s = sched.scheduler(time.time, time.sleep)
output=self.filepath
#Grab every tweet using Streaming API
with tweetstream.TweetStream(self.uname, self.password) as stream:
for tweet in stream:
if tweet.has_key("text"):
try:
#Write tweet to file and print it to STDOUT
message=tweet['text']+ "\n"
output.write(message)
print tweet['user']['screen_name'] + ": " + tweet['text'], "\n"
################################
#Timestamp code
#Timestamps should be placed once every hour
s.enter(10, 1, t.timestamp, (s,))
s.run()
except KeyError:
pass
def timestamp(self,sc):
now = datetime.datetime.now()
current_time= now.strftime("%Y-%m-%d %H:%M")
print current_time
self.filepath.write(current_time+"\n")
if __name__=='__main__':
t=twit("rohanbk","cookie","tweets.txt")
t.main()
反正我的腳本來做到這一點不經常檢查的時間每隔一分鐘使用IF語句,看看有多少時間已經過去?我是否可以使用計劃的任務,比如我如何通過對當前實施進行輕微修改來完成上述任務?