[尝试学习一些python并使用reddits api包装器PRAW编写脚本。我想发生的是生成一个提交ID的列表,当列表完成后被填充以打破循环并返回main函数。
threads = []
def main():
print("getting threads")
get_threads()
print(threads)
#create function to count threads for the for loop in get_threads so we can break out of ityes
def get_threads():
global threads
subreddit = reddit.subreddit("honestlyidk")
for submission in subreddit.stream.submissions():
if submission.id not in threads:
threads.append(submission.id)
print(threads)
else:
break
if __name__ == "__main__":
main()
现在已经坚持了几天。
在实际回答您的问题之前,请先说明:代替使用全局变量和函数来填充它,您可能应该使用一个类,并使用其构造函数或方法来填充它。
[您的问题是您选择使用subreddit.stream.submissions()
,文档中明确指出:“当有新评论时,会提供很多评论。” (https://praw.readthedocs.io/en/latest/code_overview/other/subredditstream.html)
这适用于希望在提交(实时)时获得提交的用户,即未获得当前提交列表的用户,这似乎是您想要做的。只删除else break
像其他建议的那样是行不通的,因为循环将永远循环,检查是否有新的提交。
相反,您应该执行类似的操作(否则不要修改代码):
from praw import Reddit
threads = []
reddit = Reddit(client_id='your client id',
client_secret='your secret',
user_agent='your agent')
def main():
print("getting threads")
get_threads()
print(threads)
def get_threads():
global threads, reddit
for submission in reddit.subreddit('honestlyidk').hot():
print(submission.id)
if __name__ == "__main__":
main()
我确实希望您真的没有花几天时间,但这只是过分夸大(建议:不要),因为从字面上看,这只用了一个Google文档,然后更改了该行。因为我很好奇,我花了更多时间(例如2分钟)来注册API访问。
这是一种编写您所拥有内容的方法,因此继续进行而不会使全局变量混乱(假设您希望将那些线程保留在某个地方)会容易一些:
from praw import Reddit
def main():
my_reddit = MyReddit(client_id='your client id',
client_secret='your secret',
user_agent='your agent')
print(my_reddit.get_threads())
print('Still here: ', my_reddit.threads)
class MyReddit(Reddit):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.threads = []
def get_threads(self):
self.threads = [submission.id for submission in self.subreddit('honestlyidk').hot()]
return self.threads
if __name__ == "__main__":
main()