たった1コマンド!Azure MLのサンプルコードをスマートにPython3系に対応させる方法

以前の記事「プログラミング不要!? AI(人工知能)の作り方【Azure ML – 機械学習】」でAzure MLを使ってせっかくAIを作ったのですが、このままでは毎回Azure MLを開いてログインしなければいけないのでPythonでプログラムとして使えるようにしたいと思います。

Azure MLでは作成したAIのAPIを使えるようなプログラムをある程度自動的に作ってくれるので、利用すれば簡単にプログラムにもできます!
なんて至れり尽くせり何だろうと思い、早速コードをみてみました。

import urllib2
# If you are using Python 3+, import urllib instead of urllib2import jsondata = {
“GlobalParameters”: {
“Fraction of rows in the first output dataset”: “”,
}
}body = str.encode(json.dumps(data))

url = ‘発行したWebサービスのURL’
api_key = ‘発行したAPI Key’
headers = {‘Content-Type’:’application/json’, ‘Authorization’:(‘Bearer ‘+ api_key)}

req = urllib2.Request(url, body, headers)

try:
response = urllib2.urlopen(req)

# If you are using Python 3+, replace urllib2 with urllib.request in the above code:
# req = urllib.request.Request(url, body, headers)
# response = urllib.request.urlopen(req)

result = response.read()
print(result)
except urllib2.HTTPError, error:
print(“The request failed with status code: ” + str(error.code))

# Print the headers – they include the requert ID and the timestamp, which are useful for debugging the failure
print(error.info())

print(json.loads(error.read()))

ここで、最初に気になるコメント行がありますね。以下に抜粋します。

# If you are using Python 3+, import urllib instead of urllib2

もしPython3系を利用する場合はurllib2の替わりにurllibを使ってください。
ですか・・・
困ったことに私はまさにPython3系使ってます。試しに、そのまま実行してみましたが、もちろんエラーでした。そのまま使えると思ったのにがっかりです。
でも、ここまで完成しているコードを目の前にして最初からプログラムを書くなんて手間は嫌なのでよい手段はないか調べました。

すると、標準でコンバートしてくれるプログラムが存在するとのことです!
では早速、実際に使いながらご紹介します。

実際にコンバートする

使うプログラムは「2to3.py」と呼ばれるものです。
Windowsならコマンドプロンプト、Macならターミナルを起動して以下のコマンドを叩きます。

2to3 -w 変換したいプログラムのファイルパス

Windowsの場合は、最初に「python -m 」を追加する必要があります。
たったこれだけです。とても簡単ですね!
これにより、プログラムがPython3系用に変換されて、元のプログラムのバックアップも取っておいてくれます。
実際に変換されたものがこちら

import urllib.request, urllib.error, urllib.parse
# If you are using Python 3+, import urllib instead of urllib2import jsondata = {
“GlobalParameters”: {
“Fraction of rows in the first output dataset”: “”,
}
}

body = str.encode(json.dumps(data))

url = ‘発行したWebサービスのURL’
api_key = ‘発行したAPI Key’
headers = {‘Content-Type’:’application/json’, ‘Authorization’:(‘Bearer ‘+ api_key)}

req = urllib.request.Request(url, body, headers)

try:
response = urllib.request.urlopen(req)

# If you are using Python 3+, replace urllib2 with urllib.request in the above code:
# req = urllib.request.Request(url, body, headers)
# response = urllib.request.urlopen(req)

result = response.read()
print(result)
except urllib.error.HTTPError as error:
print((“The request failed with status code: ” + str(error.code)))

# Print the headers – they include the requert ID and the timestamp, which are useful for debugging the failure
print((error.info()))

print((json.loads(error.read())))

先程のコマンドをたった一回行うだけで、赤文字のところが自動的に変換され、プログラムも無事実行できました。
これでAzure MLで作成したAIのAPIをPython3系で使用することができます!

最新情報をチェックしよう!