tly
tly

Reputation: 15

I use cmd.exe to run my script, it has an error: UnicodeDecodeError: 'utf8' codec can't decode byte 0xc9 in position 77: invalid continuation byte

#-*- coding:utf-8 -*-

import sys
sys.path.append('C:\\Users\\Karl\\workspace\\ApiRutomatedTest')
from common.SQLServerRequest import SQLServerRequest
sqlRequest = SQLServerRequest()

def getFirmCreator(env, firm_name):
   '''
   @功能:获取公司创建人名字
   '''
   sqlRequest.GetSQLSev(env)
   rows = sqlRequest.QuerySQLSev('SELECT b.Mobile from Firms a, Users b where a.CreatorId = b.Id and a.Name = \'%s\'' % firm_name)
   print rows

# getFirmCreator('LBD_SQL_SERVER', '深圳IBM')

if len(sys.argv) != 3:
   print "python GetFirmCreator.py dev/master firm_name"
elif sys.argv[1] == 'dev':
   getFirmCreator('LBD_SQL_SERVER', sys.argv[2])
elif sys.argv[1] == 'master':
   getFirmCreator('LBD_MASTER_SQL_SERVER', sys.argv[2])

This is my code, when I use eclipse to run it:

getFirmCreator('LBD_SQL_SERVER', '深圳IBM')

No error, it can tell me the correct result,the result is:

[(u'18302050001',)]

But when I use the cmd.exe to run it, like this:

C:\Users\Karl\workspace\ApiRutomatedTest\script>python GetFirmCreator.py dev 深圳IBM

It's error:

Traceback (most recent call last):
File "GetFirmCreator.py", line 28, in <module>
getFirmCreator('LBD_SQL_SERVER', sys.argv[2])
File "GetFirmCreator.py", line 20, in getFirmCreator
rows = sqlRequest.QuerySQLSev('SELECT b.Mobile from Firms a, Users b where    a.CreatorId = b.Id and a.Name = \'%s\'' % firm_name)
File "C:\Users\Karl\workspace\ApiRutomatedTest\common\SQLServerRequest.py", line 49, in QuerySQLSev
cur.execute(query_str)
File "pymssql.pyx", line 445, in pymssql.Cursor.execute (pymssql.c:6810)
File "_mssql.pyx", line 998, in _mssql.MSSQLConnection.execute_query (_mssql.c:10765)
 File "_mssql.pyx", line 1029, in _mssql.MSSQLConnection.execute_query (_mssql.c:10639)
 File "_mssql.pyx", line 1149, in_mssql.MSSQLConnection.format_and_run_query (_mssql.c:11786)
 File "_mssql.pyx", line 200, in _mssql.ensure_bytes (_mssql.c:2582)
 File "C:\Python27\lib\encodings\utf_8.py", line 16, in decode
 return codecs.utf_8_decode(input, errors, True)
 UnicodeDecodeError: 'utf8' codec can't decode byte 0xc9 in position   77:   invalid continuation byte

Upvotes: 1

Views: 273

Answers (1)

Daniel
Daniel

Reputation: 42778

Your command line arguments are encoded with the current terminal encoding, which you can get by the chcp-command.

You must first decode the arguments:

import locale
import sys
current_encoding = locale.getpreferredencoding() or 'utf8'

if len(sys.argv) != 3:
    print "python GetFirmCreator.py dev/master firm_name"
    sys.exit(1)
env = sys.argv[1]
firm_name = sys.argv[2].decode(current_encoding)
env = {
    'dev': 'LBD_SQL_SERVER',
    'master': 'LBD_MASTER_SQL_SERVER',
}[env]
getFirmCreator(env, firm_name)

Upvotes: 1

Related Questions