我有一个python脚本,该脚本不断从Twitter抓取数据并将消息写入文件.我的问题是每小时,我希望程序将当前时间写入文件.下面是我的脚本.当前,它进入了时间戳功能,并一直保持每10秒打印一次时间.
#! /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"]+ " "
output.write(message)
print tweet["user"]["screen_name"] + ": " + tweet["text"], " "
################################
#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+" ")
if __name__=="__main__":
t=twit("rohanbk","cookie","tweets.txt")
t.main()
无论如何,我的脚本是否可以执行此操作,而无需通过IF语句每隔一分钟不断检查时间来查看已花费了多少时间?我可以像上面所做的那样使用计划的任务,对当前的实现进行一些修改吗?
解决方法:
您的代码
sc.enter(10, 1, t.timestamp, (sc,)
要求在10秒内再次安排.如果您希望每小时安排一次,
sc.enter(3600, 1, t.timestamp, (sc,)
似乎更好,因为一个小时为3600秒,而不是10秒!
还行
s.enter(1, 1, t.timestamp, (s,))
每写一条推文后,都会在1秒钟后获得时间戳记-这有什么意义?只需在循环外安排一次第一次时间戳的调用,并将其周期从10秒更改为3600.
标签:file-io,python
来源: https://codeday.me/bug/20191106/2001452.html