无论何时我在Python 3中运行以下代码,都会出现语法错误
然而,当我将最后一行改成以下内容时:
我遇到了如下错误:
TypeError: POST数据应为bytes、bytes的可迭代对象或文件对象。不能为str类型。
invalid syntax
。 我认为导致这种情况的原因是Python 3中的print具有不同的语法。import sys
from urllib.request import urlopen
from urllib.request import Request
import json
request = Request(
"https://gcm-http.googleapis.com/gcm/send",
dataAsJSON,
{ "Authorization" : "key="+MY_API_KEY,
"Content-type" : "application/json"
}
)
print urlopen(request).read()
然而,当我将最后一行改成以下内容时:
result = urlopen(request).read()
我遇到了如下错误:
TypeError: POST数据应为bytes、bytes的可迭代对象或文件对象。不能为str类型。
print()
。尝试将你的字符串转换为bytearray
,可以使用以下代码:ba = urlopen(request).read().encode('latin1')
。 - Chen A.