我有一个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']+ "\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语句每隔一分钟不断检查时间来查看已花费了多少时间?我可以像上面所做的那样使用计划的任务,对当前的实现进行一些修改吗?
解决方法:
您的代码
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
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。