【问题标题】:Tweepy seems to be closing randomlyTweepy 似乎正在随机关闭
【发布时间】:2015-07-07 15:21:43
【问题描述】:

我目前正在尝试使用 tweepy 收集推文。我正在使用 tweepy 附带的基本示例程序,但是我对其进行了修改以写入文件。有时我的程序运行 12 个小时,有时运行一个,但它似乎随机关闭而没有错误消息。这是我的代码:

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'])

谢谢。

【问题讨论】:

  • 是否有可能存在某种“超时”?如果在 X 时间内没有收到包含您的 keyword 的推文,程序终止?
  • 可能是,但是我通常同时运行其中两个,关键字非常相似。一个通常关闭,另一个通常继续。
  • 并且没有错误或堆栈跟踪?
  • 什么都没有弹出,它只是关闭:(

标签: python tweepy


【解决方案1】:

使用 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)

【讨论】:

    猜你喜欢
    • 2016-02-25
    • 1970-01-01
    • 2016-04-05
    • 1970-01-01
    • 1970-01-01
    • 2016-01-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多