将"data = urllib.parse.urlencode(values)"更改为python 2.7

Joe*_*Lin 2 urllib urllib2 python-2.7 python-3.x

每一个,我都要改变一些代码从python 3.*到2.7 ,,,但是,我只是不知道data = urllib.parse.urlencode(values)python 2.7中的代码是什么

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()
Run Code Online (Sandbox Code Playgroud)

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()
Run Code Online (Sandbox Code Playgroud)

wol*_*ang 7

这是urllibpython 2.7中函数调用的等价物,它应该可以工作.

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()
Run Code Online (Sandbox Code Playgroud)

编辑:感谢@Cc L用指向上使用误差with ... asurlopen因上下文管理器没有得到执行.这是一个替代方法,其中上下文管理器在块完成时返回closing关闭the_page.