我收到这个错误,我不明白为什么.
我正在学习使用Gmail的API并复制粘贴他们的示例:https://developers.google.com/gmail/api/v1/reference/users/threads/get#examples
这是代码:
def GetThread(service, user_id, thread_id):
"""Get a Thread.
Args:
service: Authorized Gmail API service instance.
user_id: User's email address. The special value "me"
can be used to indicate the authenticated user.
thread_id: The ID of the Thread required.
Returns:
Thread with matching ID.
"""
try:
thread = service.users().threads().get(userId=user_id, id=thread_id).execute()
messages = thread['messages']
print ('thread id: %s - number of messages '
'in this thread: %d') % (thread['id'], len(messages))
return thread
except errors.HttpError, error:
print 'An error occurred: %s' % error
Run Code Online (Sandbox Code Playgroud)
我目前收到此错误:
thread id: %s - number of messages in this thread: %d
Traceback (most recent call last):
File "quickstart1.py", line 176, in <module>
main()
File "quickstart1.py", line 152, in main
GetThread(service, EMAIL_LOGIN, thread_id)
File "quickstart1.py", line 121, in GetThread
'in this thread: %d') % (thread['id'], len(messages))
TypeError: unsupported operand type(s) for %: 'NoneType' and 'tuple'
Run Code Online (Sandbox Code Playgroud)
即使我改变了
print ('thread id: %s - number of messages in this thread: %d') % (thread['id'], len(messages))
至: print ('thread id: %s - number of messages in this thread: %d') % ('test', 1)
thread id: %s - number of messages in this thread: %d
Traceback (most recent call last):
File "quickstart1.py", line 175, in <module>
main()
File "quickstart1.py", line 151, in main
GetThread(service, EMAIL_LOGIN, thread_id)
File "quickstart1.py", line 120, in GetThread
print ('thread id: %s - number of messages in this thread: %d') % ('test', 1)
TypeError: unsupported operand type(s) for %: 'NoneType' and 'tuple'
Run Code Online (Sandbox Code Playgroud)
我仍然得到同样的错误.有什么想法的原因吗?
谷歌的这个例子是为Python 2编写的,但是你在Python 3或者它上面使用它from __future__ import print_function.非常不幸的是,Google在他们的文档示例中使用了过时的Python版本,但至少从最后一个print语句中可以看出except Exception, e,并且改为except errors.HttpError, error:
特别:
print ('thread id: %s - number of messages '
'in this thread: %d') % (thread['id'], len(messages))
Run Code Online (Sandbox Code Playgroud)
是为Python 2编写的,应该改为
print(('thread id: %s - number of messages '
'in this thread: %d') % (thread['id'], len(messages)))
Run Code Online (Sandbox Code Playgroud)
在Python 3中,print是一个返回的函数None,因此将该类语句解析为
(print('something')) % (something, something)
Run Code Online (Sandbox Code Playgroud)
即操作符%应用于print元组的返回值(thread['id'], len(messages)).
但是在Python 2中,在哪里print是一个语句,print关键字之后的所有内容都会先被评估并打印出来; 所以在Python 2中,它被解析为
print (('something') % (something, something))
Run Code Online (Sandbox Code Playgroud)
在整个事物周围添加额外的括号使它在Python 3上正常工作.
如果语句没有那些额外的括号,你会得到SyntaxError:调用'print'时缺少括号"在Python中意味着什么?"这会使错误立即变得明显.