猿问

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

我是python的新手,正在尝试使用一个库。它提出了一个例外,我正在尝试确定哪个例外。这是我正在尝试的:


except tweepy.TweepError as e:

    print e

    print type(e)

    print e.__dict__

    print e.reason

    print type(e.reason)

这就是我得到的:


[{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'>

我正在尝试获取该代码。我尝试了e.reason.code,但没有成功,我也不知道要尝试什么。


富国沪深
浏览 253回答 3
3回答

aluckdog

这个怎么样?except tweepy.TweepError as e:&nbsp; &nbsp; print e.message[0]['code']&nbsp; # prints 34&nbsp; &nbsp; print e.args[0][0]['code']&nbsp; # prints 34

海绵宝宝撒

要仅获取错误代码,请使用发布的monq方法。以下示例说明了如何同时获取错误代码和消息。我必须从e.reason字符串中提取消息,如果有人有更好的方法来仅检索消息,请分享。注意:此代码应适用于以下格式的任何错误代码/原因。[{'code':50,'message':'找不到用户。'}]def getExceptionMessage(msg):&nbsp; &nbsp; words = msg.split(' ')&nbsp; &nbsp; errorMsg = ""&nbsp; &nbsp; for index, word in enumerate(words):&nbsp; &nbsp; &nbsp; &nbsp; if index not in [0,1,2]:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; errorMsg = errorMsg + ' ' + word&nbsp; &nbsp; errorMsg = errorMsg.rstrip("\'}]")&nbsp; &nbsp; errorMsg = errorMsg.lstrip(" \'")&nbsp; &nbsp; return errorMsg您可以这样称呼它:try:&nbsp; &nbsp; # Some tweepy api call, ex) api.get_user(screen_name = usrScreenName)except tweepy.TweepError as e:&nbsp; &nbsp; print (e.api_code)&nbsp; &nbsp; print (getExceptionMessage(e.reason))
随时随地看视频慕课网APP

相关分类

Python
我要回答