投稿

ラベル(utf8)が付いた投稿を表示しています

Python コメント coding:utf-8 の記述位置

Python + apache で UTF8の情報を扱っていたら SyntaxError: Non-ASCII character のエラーが多発、どうも # -*- coding: utf-8 -*- の記述位置が悪かったようで 途中に記述していたコメントを移動させて #!~/python # -*- coding: utf-8 -*- pythonのパスが先頭、次の行にcodingを記述したら動作するようになった マジックコメントって必要な場所より上にあればいいと思っていた・・・

Python で日本語を含む MySQL の select 結果を json で出力

Python で日本語を含む MySQL の select 結果を json で出力する最小限のコードをメモ Python2.7系 #!~\python2.7 # -*- coding: utf-8 -*- # utf8 output import sys import codecs sys.stdout = codecs.getwriter( 'utf_8' )(sys.stdout) # header print ( "Content-type: text/plain; charset=utf-8" ) print ( "" ) # mysql import mysql.connector import json conn = mysql.connector.connect( user = 'root' , password = 'passwd' , host = 'localhost' , database = 'myDB' ) cur = conn.cursor( dictionary = True ) try :     cur.execute( "select * from myTable;" )     rows = cur.fetchall()      print (json.dumps(rows, ensure_ascii = False )) finally :     cur.close()     conn.close() sys.stdout = codecs.getwriter('utf_8')(sys.stdout) で出力を UTF8に cursor で dictionary=True を指定することで、fetch内容に列名が入ってくるので jsonで利用しやすくなります MySQLdb を利用している場合は、cursor(MySQLdb.cursors.DictCursor) json.dumps で ensure_ascii=False を入れないと、"\u4e0d\u660e" みたいに ...