从tweepy异常实例获取错误代码

Jos*_* D. 15 python twitter tweepy python-2.7

我是python的新手,我正在尝试使用库.它提出了一个例外,我试图找出哪一个.这就是我想要的:

except tweepy.TweepError as e:
    print e
    print type(e)
    print e.__dict__
    print e.reason
    print type(e.reason)
Run Code Online (Sandbox Code Playgroud)

这就是我得到的:

[{u'message': u'Sorry, that page does not exist', u'code': 34}]
<class 'tweepy.error.TweepError'>
{'reason': u"[{u'message': u'Sorry, that page does not exist', u'code': 34}]", 'response': <httplib.HTTPResponse instance at 0x00000000029CEAC8>}
[{u'message': u'Sorry, that page does not exist', u'code': 34}]
<type 'unicode'>
Run Code Online (Sandbox Code Playgroud)

我试图达到那个代码.我试过e.reason.code没有成功,我不知道该尝试什么.

ale*_*cxe 16

这个怎么样?

except tweepy.TweepError as e:
    print e.message[0]['code']  # prints 34
    print e.args[0][0]['code']  # prints 34
Run Code Online (Sandbox Code Playgroud)

  • 这不再有效.请看我的答案. (4认同)

Jey*_*mon 11

这是2018年的情况:

args不再有效.它仍然在文档中注明,但文档已经过时,并且已经报告了该问题.目前您收到错误消息tuple.

我找到了几种可行的解决方案:

  • args[0]
    返回一个简单的代码值(类List[dict]):
    int
  • str
    返回包含代码和消息(类api_code)的文本:
    reason
  • response
    int
    分别返回一个简单的代码值(类e.message[0]['code'])和简单的消息(类message).
    'TweepError' object has no attribute 'message'
    args
  • tuple
    返回一个完整的Requests.response对象,然后可以使用Requests API通过多种方式处理它.

尽可能满足您的需求.

  • `e.api_code` 返回 `None`。至少当“状态代码 = 401”时,也许这是一个错误。 (2认同)

mon*_*onq 9

自2013年以来,情况发生了很大变化.截至目前,正确的答案是使用e.api_code.