2016-06-16 8 views
1

に変更すると、Python 3からいくつかのコードを変更する必要があります。* * 2.7になります。 Pythonでコードdata = urllib.parse.urlencode(values) 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() 

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() 

答えて

6

ここで動作するはずの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() 

編集:原因コンテキストマネージャ実装されていないにurlopenwith ... asを使用して、エラーを指してくれてありがとう@Cc L。コンテキストマネージャがclosingで返され、ブロックの完了時にthe_pageが終了する別の方法があります。 urllib2.urlopenと

+0

おかげで作業することができ、最初に,,あなたのコードはほとんどが正しい、と私は考える」(REQ )を "response = urllib2.urlopen(req)"に変更する必要があります。そうでなければ、 "AttributeError:addinfourlインスタンスに属性 '__exit__'がありません"というエラーが発生します。 –

0

上記でwolfsgangの答えのためのおかげで、私は私のコードを変更し、それはあなたの答えのために

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)