使用python多进程处理twitter api调用
我想在twitter搜索API上进行多过程处理。 我有下面的代码,它做一次调用,而不是多次调用使用python多进程处理twitter api调用,python,twitter,Python,Twitter,我想在twitter搜索API上进行多过程处理。 我有下面的代码,它做一次调用,而不是多次调用 from multiprocessing import Process from twitter import * config = {} exec(compile(open("config.py", "rb").read(), "config.py", 'exec'), config) twitter = Twitter( auth=OAuth(config["access_key"],
from multiprocessing import Process
from twitter import *
config = {}
exec(compile(open("config.py", "rb").read(), "config.py", 'exec'), config)
twitter = Twitter(
auth=OAuth(config["access_key"], config["access_secret"], config["consumer_key"], config["consumer_secret"]))
def twitterSearch(word):
tweetsWithWord = twitter.search.tweets(q=word, count=100)
print(tweetsWithWord)
if __name__ == '__main__':
for i in range(8):
p = Process(target=twitterSearch, args=('racist',))
p.start()
p.join()
请帮我解决这个问题。如果我理解正确,您需要的是为您的搜索词提供连续的搜索结果流。我不知道你正在使用的软件包,但我知道这两者都可以使用twitter的流媒体API 在任何情况下,您都需要处理流中出现的每一条tweet,如果需要,您可以在该阶段使用进程/线程 流式处理的代码示例:
from threading import Thread
from queue import Queue
from twython import TwythonStreamer
from requests.exceptions import ChunkedEncodingError
CONSUMER_KEY = 'AAA'
CONSUMER_SECRET = 'BBB'
ACCESS_KEY = 'CCC'
ACCESS_SECRET = 'DDD'
class TwitterStream(TwythonStreamer):
def __init__(self, consumer_key, consumer_secret, token, token_secret, tqueue):
self.tweet_queue = tqueue
super(TwitterStream, self).__init__(consumer_key, consumer_secret, token, token_secret)
def on_success(self, data):
if 'text' in data:
self.tweet_queue.put(data)
def on_error(self, status_code, data):
#print(status_code)
#with open(logfile,'a') as f:
# f.write(time.asctime(time.gmtime()) + ' ' + status_code + '\n')
# Want to stop trying to get data because of the error?
# Uncomment the next line!
# self.disconnect()
pass
def stream_tweets(tweets_queue,track):
# Input your credentials below
consumer_key = CONSUMER_KEY
consumer_secret = CONSUMER_SECRET
token = ACCESS_KEY
token_secret = ACCESS_SECRET
try:
stream = TwitterStream(consumer_key, consumer_secret, token, token_secret, tweets_queue)
stream.statuses.filter(track=track)
except ChunkedEncodingError:
# Sometimes the API sends back one byte less than expected which results in an exception in the
# current version of the requests library
stream_tweets(tweet_queue)
def process_tweets(tweets_queue, reply_dict, api, logfile):
while True:
twt = tweets_queue.get()
# Do something with the tweet
# You can start a new thread for actually proccessing each tweet
tweets_queue.task_done()
tweet_queue = Queue()
track = 'whatever you want to filter by' # Search terms go here
Thread(target=stream_tweets,
args=(tweet_queue, track,),
daemon=True).start()
process_tweets(tweet_queue, reply_dict, api, logfile)
您在Windows上吗?是的,我在使用Windows。问题是您每次创建一个循环并在该循环中生成一个进程,而不是一次启动所有进程。但我意识到,我认为我对您正在使用的API了解不够,无法为您提供答案;我不知道你想做什么,也不知道会有什么回报。在Windows方面,我发现
p.join()
本身可能会导致问题,因为没有os.fork()
,所以将其删除。我相信您需要的是多线程而不是多进程处理。然而,当前代码的主要问题是等待进程完成。你可以使用process,我用了@MusicGindos