Python tweepy写入到sqlite3 db

Python tweepy writing to sqlite3 db(Python tweepy写入到sqlite3 db)
本文介绍了Python tweepy写入到sqlite3 db的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我下面的脚本(摘自各种在线资源)没有写入数据库。我没有收到任何错误,如果我注释掉数据库行,则它会毫无问题地输出到控制台。

数据库存在,它有2个字段,可由我写入...有什么想法吗?

已更新以下代码

#!/usr/bin/env python

import sys
import tweepy
from textwrap import TextWrapper
import sqlite3

CONSUMER_KEY = ''
CONSUMER_SECRET = ''
ACCESS_KEY = ''
ACCESS_SECRET = ''


auth1 = tweepy.auth.OAuthHandler(CONSUMER_KEY,CONSUMER_SECRET)
auth1.set_access_token(ACCESS_KEY,ACCESS_SECRET)
api = tweepy.API(auth1)
conn = sqlite3.connect('twitter.db')
cur = conn.cursor()

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



    def on_status(self, status):
        try:
            cur.execute('INSERT INTO tweets (text, date) VALUES (?, ?)' ,(status.text,))
            print self.status_wrapper.fill(status.text)
            print '
 %s  %s  via %s
' % (status.author.screen_name, status.created_at, status.source)
            conn.commit()   
        except Exception, e:
            print >> sys.stderr, 'Encountered Exception:', e

    def on_error(self, status_code):
            print >> sys.stderr, 'Encountered error with status code:', status_code
            return True # Don't kill the stream

    def on_timeout(self):
            print >> sys.stderr, 'Timeout...'
            return True # Don't kill the stream


streamer = tweepy.Stream(auth1, StreamListener(), timeout=None)
setTerms = ['news','hello']
streamer.filter(setTerms)

推荐答案

首先,修复缩进。您不会收到任何错误,因为您显式地让它们静默了!使用

except Exception, e:
    # Catch any unicode errors while printing to console
    # and just ignore them to avoid breaking application.
    pass

这将捕获try: except:块中发生的任何异常。阅读Python教程是一项good start to learn more about exceptions.

这篇关于Python tweepy写入到sqlite3 db的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Leetcode 234: Palindrome LinkedList(Leetcode 234:回文链接列表)
How do I read an Excel file directly from Dropbox#39;s API using pandas.read_excel()?(如何使用PANDAS.READ_EXCEL()直接从Dropbox的API读取Excel文件?)
subprocess.Popen tries to write to nonexistent pipe(子进程。打开尝试写入不存在的管道)
I want to realize Popen-code from Windows to Linux:(我想实现从Windows到Linux的POpen-code:)
Reading stdout from a subprocess in real time(实时读取子进程中的标准输出)
How to call type safely on a random file in Python?(如何在Python中安全地调用随机文件上的类型?)