1

我正在使用 Reddit api 来支持一些 subreddit。我想同时支持多个 subreddits,使用该praw库与 reddit api 交互。

我想为 /r/bookclub 的 27 个“热门”和“上升”帖子投票:

subreddit = reddit.subreddit("bookclub")

for submission in subreddit.hot(limit=27):
    submission.upvote()

for submission in subreddit.rising(limit=27):
    submission.upvote()

我想使用异步或多处理来更快地做到这一点。我使用该grequests.upvote()一次完成所有工作,到目前为止它正在工作,但我不确定它是否真的更好:

subreddit = reddit.subreddit("bookclub")

hot_upvotes = (grequests.get(submission.upvote()) for submission in subreddit.hot(limit=27))
grequests.map(hot_upvotes)

rising_upvotes = (grequests.get(submission.upvote()) for submission in subreddit.rising(limit=27))
grequests.map(rising_upvotes)

两个版本都支持 subreddit。我想知道是否可以同时运行hot_upvotesrising_upvotes部分?

4

1 回答 1

1
from threading import Thread
import functools

subreddit = reddit.subreddit("bookclub")

def run_hot_upvotes(subreddit):
    hot_upvotes = (grequests.get(submission.upvote()) for submission in subreddit.hot(limit=27))
    grequests.map(hot_upvotes)

def run_rising_upvotes(subreddit):
    rising_upvotes = (grequests.get(submission.upvote()) for submission in subreddit.rising(limit=27))
    grequests.map(rising_upvotes)

Thread(target = functools.partial(run_rising_upvotes, subreddit)).start()
Thread(target = functools.partial(run_hot_upvotes, subreddit)).start()

尝试以下操作以使两者同时运行,每个都在自己的线程中。

于 2017-05-17T21:49:03.720 回答