python2系(Windows)のコマンドライン引数で日本語を取り扱う

Published on:
Last updated:

This post is also available in: 日本語 (Japanese)

Windows環境でPython2系(Python3系はまた文字コードの取り扱い方法が異なる)を使って開発していて、コマンドライン引数で日本語を取り扱う際に少し困ったので、メモとして書いています。

そもそものややこしい原因は、Windowsでは "cp932" という文字コードShift_JIS のWindows版みたいな設定になっている事が原因で、また python での日本語扱う際のエンコード/デコードのややこしさもあります。

以下の例では、コマンドプロンプト使ってます。
設定にもよると思いますがGit Bashとか使うとエラーが出ました。

#sample.py
#!/usr/bin/env python
# coding: utf-8
import sys

args = sys.argv

print args
print args[0]
text = args[1].decode('cp932')
print text
print args[2]

"""
#コマンドプロンプトでの入力
C:\Users\sample>python sample.py 食パン syokupan
"""
"""
#以下出力結果
['C:\\Users\\sample\\sample.py', '\x82\xb5\x82\xe5\x82\xad\x82\xcf\x82\xf1', 'syokupan'] #args
C:\Users\sample\sample.py #args[0]
食パン #args[1]
syokupan #args[2]
"""
No tags for this post.

About
Kuniyoshi Takemoto is the founder of Amelt.net LLC, and editor of this blog(www.amelt.net).Learn more and follow me on LinkedIn.