我在 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 我想把它们放到数据库或文本文件中。
最佳答案
好吧,这看起来像是一个很好的例子,说明为什么做一个简单的 try/except
是个坏主意。
首先,如果在打印期间确实发生了任何 UnicodeDecodeError
,也不会向您的文件写入任何内容,因为该部分代码将被跳过。
其次,如果发生任何其他异常,您甚至不会注意到它,因为您会默默地捕获(并忽略)所有异常。
至少如此
except UnicodeDecodeError:
print "Record skipped!"
并查看可能发生的其他(如果有)异常。
关于python - 在 python 2.7 中,信息不会从 twitter 写入文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11493068/