Skip to main content
 首页 » 编程设计

python之在 while 循环中处理异常之Python

2025年05月04日17arxive

这是我的代码(@cdhowie 的几乎完整版本:)):

def getResult(method, argument=None): 
  result = None 
 
  while True: 
    print('### loop') 
    try: 
      print ('### try hard...') 
      if argument: 
        result = method(argument) 
      else: 
        result = method() 
      break 
    except Exception as e: 
      print('### GithubException') 
      if 403 == e.status: 
        print('Warning: ' + str(e.data)) 
        print('I will try again after 10 minutes...') 
      else: 
        raise e 
 
  return result 
 
def getUsernames(locations, gh): 
  usernames = set() 
 
  for location in locations: 
    print location 
    result = getResult(gh.legacy_search_users, location) 
    for user in result: 
      usernames.add(user.login) 
      print user.login, 
 
  return usernames 
 
# "main.py" 
gh = Github() 
locations = ['Washington', 'Berlin'] 
# "main.py", line 12 is bellow 
usernames = getUsernames(locations, gh) 

问题是,出现了异常,但我无法处理它。这是一个输出:

### loop 
### try hard... 
Traceback (most recent call last): 
  File "main.py", line 12, in <module> 
    usernames = getUsernames(locations, gh) 
  File "/home/ciembor/projekty/github-rank/functions.py", line 39, in getUsernames 
    for user in result: 
  File "/usr/lib/python2.7/site-packages/PyGithub-1.8.0-py2.7.egg/github/PaginatedList.py", line 33, in __iter__ 
    newElements = self.__grow() 
  File "/usr/lib/python2.7/site-packages/PyGithub-1.8.0-py2.7.egg/github/PaginatedList.py", line 45, in __grow 
    newElements = self._fetchNextPage() 
  File "/usr/lib/python2.7/site-packages/PyGithub-1.8.0-py2.7.egg/github/Legacy.py", line 37, in _fetchNextPage 
    return self.get_page(page) 
  File "/usr/lib/python2.7/site-packages/PyGithub-1.8.0-py2.7.egg/github/Legacy.py", line 48, in get_page 
    None 
  File "/usr/lib/python2.7/site-packages/PyGithub-1.8.0-py2.7.egg/github/Requester.py", line 69, in requestAndCheck 
    raise GithubException.GithubException(status, output) 
github.GithubException.GithubException: 403 {u'message': u'API Rate Limit Exceeded for 11.11.11.11'} 

为什么不打印### handling exception?

请您参考如下方法:

仔细查看异常中的堆栈跟踪:

Traceback (most recent call last): 
  File "main.py", line 12, in <module> 
    usernames = getUsernames(locations, gh) 
  File "/home/ciembor/projekty/github-rank/functions.py", line 39, in getUsernames 
    for user in result: 
  File "/usr/lib/python2.7/site-packages/PyGithub-1.8.0-py2.7.egg/github/PaginatedList.py", line 33, in __iter__ 
    newElements = self.__grow() 
  ... 

for user in result: after getResult 完成执行后,异常从行调用的代码中抛出。这意味着您正在使用的 API 正在使用惰性评估,因此实际的 API 请求不会在您期望的时候发生。

为了捕获和处理这个异常,您需要使用 try/except 将代码包装在 getUsernames 函数中处理程序。