2

我在使用以下代码时遇到问题:

import praw
import argparse

# argument handling was here

def main():
    r = praw.Reddit(user_agent='Python Reddit Image Grabber v0.1')
    for i in range(len(args.subreddits)):
        try:
            r.get_subreddit(args.subreddits[i]) # test to see if the subreddit is valid
        except:
            print "Invalid subreddit"
        else:
            submissions = r.get_subreddit(args.subreddits[i]).get_hot(limit=100)
            print [str(x) for x in submissions]

if __name__ == '__main__':
    main()

subreddit名称被当作程序的参数。

当一个无效args.subreddits值被传递给 时get_subreddit,它会抛出一个应该在上面的代码中捕获的异常。

当一个有效的args.subreddit名字作为参数给出时,程序运行良好。

但是当给定一个无效的args.subreddit名称时,不会抛出异常,而是输出以下未捕获的异常。

Traceback (most recent call last):
  File "./pyrig.py", line 33, in <module>
    main()
  File "./pyrig.py", line 30, in main
    print [str(x) for x in submissions]
  File "/usr/local/lib/python2.7/dist-packages/praw/__init__.py", line 434, in get_content
    page_data = self.request_json(url, params=params)
  File "/usr/local/lib/python2.7/dist-packages/praw/decorators.py", line 95, in wrapped
    return_value = function(reddit_session, *args, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/praw/__init__.py", line 469, in request_json
    response = self._request(url, params, data)
  File "/usr/local/lib/python2.7/dist-packages/praw/__init__.py", line 342, in _request
    response = handle_redirect()
  File "/usr/local/lib/python2.7/dist-packages/praw/__init__.py", line 316, in handle_redirect
    url = _raise_redirect_exceptions(response)
  File "/usr/local/lib/python2.7/dist-packages/praw/internal.py", line 165, in _raise_redirect_exceptions
    .format(subreddit))
praw.errors.InvalidSubreddit: `soccersdsd` is not a valid subreddit

我不能说我做错了什么。我也尝试将异常代码重写为

except praw.errors.InvalidSubreddit:

这也不起作用。

编辑:Praw 的异常信息可以在这里找到

4

1 回答 1

2
File "./pyrig.py", line 30, in main
  print [str(x) for x in submissions]

正如您的回溯所表明的那样,问题是您调用时不会发生异常get_subreddit实际上,调用时也不会发生异常get_hot。第一个是惰性调用,它只创建一个虚拟Subreddit对象,但不对其进行任何操作。第二个是一个生成器,它在您实际尝试迭代它之前不会发出任何请求。

因此,您需要在您的打印语句(第 30 行)周围移动异常处理代码,这是实际发出导致异常的请求的位置。

于 2013-06-01T00:11:37.477 回答