每一个,我都要将一些代码从python 3. *更改为2.7 ,,,但是,我只是不知道python 2.7中的代码data = urllib.parse.urlencode(values)
是什么
python3。*
import urllib.parse
import urllib.request
def sendsms(phonenumber,textcontent):
url = 'http://urls?'
values = {'username' : 'hello',
'password' : 'world',
'dstaddr' : phonenumber ,
'smbody': textcontent
}
data = urllib.parse.urlencode(values)
data = data.encode('Big5')
req = urllib.request.Request(url, data)
with urllib.request.urlopen(req) as response:
the_page = response.read()
python 2.7
from urlparse import urlparse
from urllib2 import urlopen
from urllib import urlencode
def sendsms(phonenumber,textcontent):
url = 'http://urls?'
values = {'username' : 'hello',
'password' : 'world',
'dstaddr' : phonenumber ,
'smbody': textcontent
}
data = urllib.parse.urlencode(values) #python 3.* code, what about python 2.7 ?
data = data.encode('Big5')
req = urllib.request.Request(url, data)
with urllib.request.urlopen(req) as response:
the_page = response.read()
答案 0 :(得分:7)
这是python 2.7中urllib
函数调用的等价物,它应该可以工作。
import urllib
import urllib2
from contextlib import closing
def sendsms(phonenumber,textcontent):
url = 'http://urls?'
values = {'username' : 'hello',
'password' : 'world',
'dstaddr' : phonenumber ,
'smbody': textcontent
}
data = urllib.urlencode(values)
data = data.encode('Big5')
req = urllib2.Request(url, data)
with closing(urllib2.urlopen(req)) as response:
the_page = response.read()
编辑:由于上下文管理器未实现,感谢@Cc L指出错误使用with ... as
和urlopen
。这是一个替代方法,其中上下文管理器返回,closing
在块完成时关闭the_page
。
答案 1 :(得分:0)
import urllib
import urllib2
def sendsms(phonenumber,textcontent):
url = 'http://urls?'
values = {'username' : 'hello',
'password' : 'world',
'dstaddr' : phonenumber ,
'smbody': textcontent
}
data = urllib.urlencode(values)
data = data.encode('Big5')
req = urllib2.Request(url, data)
response = urllib2.urlopen(req)