Tweepy 似乎随机关闭
Tweepy seems to be closing randomly
我目前正在尝试使用 tweepy 收集推文。我正在使用 tweepy 附带的基本示例程序,但是我修改了它以写入文件。有时我的程序运行 12 小时,有时运行 1 小时,但它似乎随机关闭且没有错误消息。这是我的代码:
from __future__ import absolute_import, print_function
from tweepy.streaming import StreamListener
from tweepy import OAuthHandler
from tweepy import Stream
# Go to http://apps.twitter.com and create an app.
# The consumer key and secret will be generated for you after
consumer_key=""
consumer_secret=""
# After the step above, you will be redirected to your app's page.
# Create an access token under the the "Your access token" section
access_token=""
access_token_secret=""
f = open('filename.txt', 'w')
class StdOutListener(StreamListener):
""" A listener handles tweets are the received from the stream.
This is a basic listener that just prints received tweets to stdout.
"""
def on_data(self, data):
print(data)
f.write(data)
return True
def on_error(self, status):
print(status)
if __name__ == '__main__':
l = StdOutListener()
auth = OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
stream = Stream(auth, l)
stream.filter(track=['keyword'])
谢谢。
使用 try, except 块,您的 Stream 错误将打印到 STDOUT。您可以在 except 块中捕获错误并重新启动脚本,或者记录错误。
try:
stream.filter(track=['keyword'])
except Exception, e:
print "error: %s" % str(e)
# log error or restart script
我猜测它崩溃的原因是由于一个类似的常见错误:
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe7 in position 4: ordinal not in range(128)
我目前正在尝试使用 tweepy 收集推文。我正在使用 tweepy 附带的基本示例程序,但是我修改了它以写入文件。有时我的程序运行 12 小时,有时运行 1 小时,但它似乎随机关闭且没有错误消息。这是我的代码:
from __future__ import absolute_import, print_function
from tweepy.streaming import StreamListener
from tweepy import OAuthHandler
from tweepy import Stream
# Go to http://apps.twitter.com and create an app.
# The consumer key and secret will be generated for you after
consumer_key=""
consumer_secret=""
# After the step above, you will be redirected to your app's page.
# Create an access token under the the "Your access token" section
access_token=""
access_token_secret=""
f = open('filename.txt', 'w')
class StdOutListener(StreamListener):
""" A listener handles tweets are the received from the stream.
This is a basic listener that just prints received tweets to stdout.
"""
def on_data(self, data):
print(data)
f.write(data)
return True
def on_error(self, status):
print(status)
if __name__ == '__main__':
l = StdOutListener()
auth = OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
stream = Stream(auth, l)
stream.filter(track=['keyword'])
谢谢。
使用 try, except 块,您的 Stream 错误将打印到 STDOUT。您可以在 except 块中捕获错误并重新启动脚本,或者记录错误。
try:
stream.filter(track=['keyword'])
except Exception, e:
print "error: %s" % str(e)
# log error or restart script
我猜测它崩溃的原因是由于一个类似的常见错误:
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe7 in position 4: ordinal not in range(128)