views:

28

answers:

4
from getpass import getpass
from textwrap import TextWrapper
import tweepy
import time

class StreamWatcherListener(tweepy.StreamListener):
    status_wrapper = TextWrapper(width=60, initial_indent='    ', subsequent_indent='    ')
    def on_status(self, status):
        try:
            print self.status_wrapper.fill(status.text)
            print '\n %s  %s  via %s\n' % (status.author.screen_name, status.created_at, status.source)
        except:
            # Catch any unicode errors while printing to console
            # and just ignore them to avoid breaking application.
            pass
    def on_error(self, status_code):
        print 'An error has occured! Status code = %s' % status_code
        return True  # keep stream alive
    def on_timeout(self):
        print 'Snoozing Zzzzzz'



username="abc"
password="abc"
auth = tweepy.BasicAuthHandler(username, password)
listener = StreamWatcherListener()
stream=tweepy.Stream(auth,listener)
stream.filter(locations=[-122.75,36.8,-121.75,37.8,-74,40,-73,41])

This just prints to console. But what if I want to do more with it? The library I'm using is here.

+1  A: 

You are using print statements.

Open a file and write the string that you are printing to console

[Edit:]

See the example below and also

read about file I/O at : http://diveintopython.org/file_handling/file_objects.html

In your code

class StreamWatcherListener(tweepy.StreamListener):
    status_wrapper = TextWrapper(width=60, initial_indent='    ', subsequent_indent='    ')

    def __init__(self, api=None):
        self.file = open("myNewFile")
        super(StreamWatcherListener, self).__init__(api)

    ....
pyfunc
A: 

Don't use print. instead write to a file.

file = open("myNewFile")
file.write("hello")
kasten
A: 
#....

    class StreamWatcherListener(tweepy.StreamListener):
        status_wrapper = TextWrapper(width=60, initial_indent='    ', subsequent_indent='    ')

        def __init__(self, api=None):
            self.file = open("myNewFile")#!!!
            super(StreamWatcherListener, self).__init__(api)

        def on_status(self, status):
            try:#!!!
                self.file.write(str(self.status_wrapper.fill(status.text)))
                self.file.write('\n %s  %s  via %s\n' % (status.author.screen_name, status.created_at, status.source))

#....
seriyPS
A: 

Note that you can print to a file with almost no changes:

import sys

sys.stdout = open('myFile', 'w')
print 'hello'

This will write hello to myFile.

Antoine Pelisse