I have a python script that constantly captures data from Twitter and writes messages to a file. The question I have is every hour, I want my program to write the current time to a file. Below is my script. Currently, it falls into the timestamp function and just keeps printing time every 10 seconds.
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
with tweetstream.TweetStream(self.uname, self.password) as stream:
for tweet in stream:
if tweet.has_key("text"):
try:
message=tweet['text']+ "\n"
output.write(message)
print tweet['user']['screen_name'] + ": " + tweet['text'], "\n"
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()
Anyway, for my script to do this without checking the time every minute with the IF statement to find out how much time has passed? Can I use a scheduled task, for example, as it was done above, with a slight modification of my current implementation?
source
share