Python问题与保存输出

时间:2014-10-31 13:41:12

标签: python stdout tweepy

作为Python的新用户,我遇到了以下代码的问题。我不需要只在屏幕上打印Twitter搜索的结果,而是需要保存文件(理想情况下是管道分隔的,我还不知道如何生成......)。但是,以下代码运行正常但不创建Output.txt文件。它做了一次然后再也没有。我在Mac OS上运行它并用Ctrl + C结束代码(因为我仍然不知道如何修改它只返回特定数量的推文)。我认为这个问题可能与Flush'ing有关,但在尝试包括这篇文章中的选项之后:Flushing issues它们似乎都没有用(除非我做错了,这很可能......) / p>

import tweepy
import json
import sys

# Authentication details. To  obtain these visit dev.twitter.com
consumer_key = 'xxxxxx'
consumer_secret = 'xxxxx'
access_token = 'xxxxx-xxxx'
access_token_secret = 'xxxxxxxx'

# This is the listener, resposible for receiving data
class StdOutListener(tweepy.StreamListener):
    def on_data(self, data):
        # Twitter returns data in JSON format - we need to decode it first
        decoded = json.loads(data)

        # Also, we convert UTF-8 to ASCII ignoring all bad characters sent by users
        print '@%s: %s' % (decoded['user']['screen_name'], decoded['text'].encode('ascii', 'ignore'))
        print ''
        return True

    def on_error(self, status):
        print status

if __name__ == '__main__':
    l = StdOutListener()
    auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
    auth.set_access_token(access_token, access_token_secret)

    print "Showing all new tweets for #Microsoft"

    stream = tweepy.Stream(auth, l)
    stream.filter(track=['Microsoft'])

    sys.stdout = open('Output.txt', 'w')

1 个答案:

答案 0 :(得分:2)

我认为你会更好地跟踪StdOutListener并让它直接写入文件。将sys.stdout分配给文件是......很奇怪。这样,您可以print调试输出。另请注意文件模式" w"将在文件打开时截断文件。

class TweepyFileListener(tweepy.StreamListener):
    def on_data(self, data):
        print "on_data called"
        # Twitter returns data in JSON format - we need to decode it first
        decoded = json.loads(data)
        msg = '@%s: %s\n' % (
            decoded['user']['screen_name'], 
            decoded['text'].encode('ascii', 'ignore'))

        #you should really open the file in __init__
        #You should also use a RotatingFileHandler or this guy will get massive
        with open("Output.txt", "a") as tweet_log:
            print "Received: %s\n" % msg
            tweet_log.write(msg)