1

我有一个 python 项目,我试图使用 Python 2.7 从 IDLE 运行当我运行程序时,确实会按照我的意愿创建一个文本文件,但没有写入任何信息,我不明白为什么会这样. 我通过在我的 Ubuntu 12.04 LTS 笔记本电脑上按 IDLE 中的 F5 键将它作为一个模块运行。

这是代码:

import time
import MySQLdb
import tweepy
from tweepy.streaming import StreamListener
from tweepy import OAuthHandler
from tweepy import Stream

# Go to http://dev.twitter.com and create an app.
# The consumer key and secret will be generated for you after
consumer_key=" # Omitted "
consumer_secret=" # Omitted "

# 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=" # Omitted "
access_token_secret=" # Omitted "

auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)

api = tweepy.API(auth)

# If the authentication was successful, you should
# see the name of the account print out
print api.me().name

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
            return True

        def on_error(self, status):
            print status

if __name__ == '__main__':
        l = StdOutListener()

        stream = Stream(auth, l)    
        stream.filter(track=['#google'])

如果有人想在 github 上与我一起工作,我在 github 上的文件: stocktwitterdb.py

可以在 github 上找到使用 tweepy 的流式传输示例: tweepy streaming.py

现在我在 shell 中遇到了一些事情,我想将它们放入数据库或文本文件中。

4

3 回答 3

3

好吧,这看起来像是一个很好的例子,说明为什么做一个 bare 是个坏主意try/except

首先,如果在打印过程中确实发生了任何事情,则不UnicodeDecodeError会将任何内容写入您的文件,因为这部分代码将被跳过。

其次,如果发生任何其他异常,您甚至不会注意到它,因为您会默默地捕获(并忽略)所有异常。

所以至少做

except UnicodeDecodeError:
    print "Record skipped!"

并查看可能发生的其他(如果有)异常。

于 2012-07-15T15:31:24.463 回答
0
import time
import MySQLdb
import tweepy
from textwrap import TextWrapper
from getpass import getpass

qParam = "Twitter"

def __init__(self, target):
    super(StockTweetListener, self).__init__();
    self.target = target

with open('results.txt', 'w') as f:
    while True:
        stream = tweepy.Stream(username, password, StockTweetListener(target), timeout=None);
        stream.filter(None, stock_list)
target.truncate()

def debug_print(text):
    """Print text if debugging mode is on"""
    if settings.debug:
        print text

class StockTweetListener(tweepy.StreamListener):

    status_wrapper = TextWrapper(width=60, initial_indent=' ', subsequent_indent=' ')

    def on_status(self, status):
        try:
            # print 'Status : %s' %(self.status_wrapper.fill(status.text))
            print '\nStatus : %s' %(status.text)            
            print '\nAuthor : %s' %(status.author.screen_name)
            print '\nDate/Time : %s' %(status.created_at)
            print '\nSource : %s' %(status.source)           
            print '\nGeo : %s' %(status.geo)
            print '\n\n\n-----------------------------------------------------------------------------\n\n\n'

            l1 = '\nStatus : %s' %(status.text)            
            l2 = '\nAuthor : %s' %(status.author.screen_name)
            l3 = '\nDate/Time : %s' %(status.created_at)
            l4 = '\nSource : %s' %(status.source)           
            l5 = '\nGeo : %s' %(status.geo)
            l6 = '\n\n\n-----------------------------------------------------------------------------\n\n\n'

            target.write(l1)
            target.write(l2)
            target.write(l3)
            target.write(l4)
            target.write(l5)
            target.write(l6)                                    

        except UnicodeDecodeError:
            # 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
        target.close()
        return True # keep stream alive

    def on_timeout(self):
        print 'Snoozing Zzzzzz'
        target.close()





def main():
    username = raw_input('Twitter username: ')
    password = getpass('Twitter password: ')
    stock = raw_input('Name of Stocks(comma seperated): ')
    stock_list = [u for u in stock.split(',')]




    stream = tweepy.Stream(username, password, StockTweetListener(target), timeout=None)
#    follow_list = None
    stream.filter(None, stock_list)



if __name__ == '__main__':
    try:
        main()
    except KeyboardInterrupt:
        target.close()
        quit()

这会产生错误

于 2012-07-16T13:55:34.163 回答
0

您需要进行的更改有些混乱,所以我将在此处发布一个希望修复的版本,以及一些关于为什么事情会这样的评论。

import time
import MySQLdb # also not currently used
import tweepy
from textwrap import TextWrapper # not used currently
from getpass import getpass

# define the format for messages here to avoid repetition
OUT_STR = '''
Status : %(text)s
Author : %(author)s
Date/Time : %(date)s
Source : %(source)s
Geo : %(geo)s


-----------------------------------------------------------------------------


'''

class StockTweetListener(tweepy.StreamListener):
    def __init__(self, target):
        super(StockTweetListener, self).__init__();
        self.target = target
        # status_wrapper = TextWrapper(width=60, initial_indent=' ',
        #                             subsequent_indent=' ')
        # This isn't used in the current code. But, if you were going
        # to use it, you'd need to assign it to self.status_wrapper;
        # otherwise the variable would be local to this __init__ method
        # and inaccessible from anything else.

    def on_status(self, status):
        try:
            msg = OUT_STR % {
                'text': status.text,
                'author': status.author.screen_name,
                'date': status.created_at,
                'source': status.source,
                'geo': status.geo,
            }
            print msg
            self.target.write(msg)
            # use self.target here. self is one of the paramaters to this
            # method and refers to the object; because you assigned to its
            # .target attribute before, you can use it here.

        except UnicodeDecodeError:
            # Catch any unicode errors while printing to console
            # and just ignore them to avoid breaking application.
            print "Record Skipped"

    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'

def main():
    username = raw_input('Twitter username: ')
    password = getpass('Twitter password: ')
    stock = raw_input('Name of Stocks(comma seperated): ')
    stock_list = [u for u in stock.split(',')]
    follow_list = None # ??? you don't seem to define this variable

    # open results.txt here and name it f locally. once code flow leaves
    # the with statement, in this case only through an exception happening
    # that jumps you out of the while loop, the file will be closed.
    with open('results.txt', 'w') as f:
         while True:
             stream = tweepy.Stream(
                            username, password,
                            StockTweetListener(f), # passes the file to __init__
                                                   # as the "target" argument
                            timeout=None)
             stream.filter(follow_list, stock_list)

if __name__ == '__main__':
    try:
        main()
    except KeyboardInterrupt:
        quit()
于 2012-07-18T16:38:23.363 回答