Python3中代码:
CreateTableSqlTemplate = """CREATE TABLE IF NOT EXISTS `%s` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT COMMENT ‘自增,主键’,
`cityDealerPrice` int(11) unsigned NOT NULL DEFAULT ‘0’ COMMENT ‘经销商参考价’,
`msrpPrice` int(11) unsigned NOT NULL DEFAULT ‘0’ COMMENT ‘厂商指导价’,
`mainBrand` char(20) NOT NULL DEFAULT ” COMMENT ‘品牌’,
`subBrand` varchar(20) NOT NULL DEFAULT ” COMMENT ‘子品牌’,
`brandSerie` varchar(20) NOT NULL DEFAULT ” COMMENT ‘车系’,
`brandSerieId` varchar(15) NOT NULL DEFAULT ” COMMENT ‘车系ID’,
`model` varchar(50) NOT NULL DEFAULT ” COMMENT ‘车型’,
`modelId` varchar(15) NOT NULL DEFAULT ” COMMENT ‘车型ID’,
`modelStatus` char(5) NOT NULL DEFAULT ” COMMENT ‘车型状态’,
`url` varchar(200) NOT NULL DEFAULT ” COMMENT ‘车型url’,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;"""
logging.info("config=%s, needCreateTable=%s, tableName=%s, createTableSqlTemplate=%s",
config, needCreateTable, tableName, createTableSqlTemplate)
结果出错:
<span style="font-family: Monaco; font-size: 12px; color: rgb(51, 51, 51);"–<- Logging error —
Traceback (most recent call last):
File "/usr/local/Cellar/python/3.6.4_4/Frameworks/Python.framework/Versions/3.6/lib/python3.6/logging/__init__.py", line 994, in emit
stream.write(msg)
UnicodeEncodeError: ‘ascii’ codec can’t encode characters in position 334-338: ordinal not in range(128)
然后
试了试:
logging.info("createTableSqlTemplate=%s", createTableSqlTemplate.encode("utf-8"))
结果:
createTableSqlTemplate=b"CREATE TABLE IF NOT EXISTS `%s` (….
输出了bytes,是不会出错,但是输出到都是\xxxx,不方便查看原始内容了。
然后也试了试加u前缀:
CreateTableSqlTemplate = u"""CREATE TABLE IF NOT EXISTS `%s` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT COMMENT ‘自增,主键’。。。。"""
问题依旧。
所以想要搞清楚Python3中,如何声明是unicode字符串
python 3 unicode string
python 3 declare unicode string
python – How to make unicode string with python3 – Stack Overflow
试试:
logging.info("createTableSqlTemplate=%s", str(createTableSqlTemplate))
结果问题依旧。
How to print unicode escape sequence from unicode strings in python(3)? – Stack Overflow
试试:
CreateTableSqlTemplate = b”""xxx""".decode("utf-8")
结果:
SyntaxError: bytes can only contain ASCII literal characters.
试试:
CreateTableSqlTemplate = “""xxx""".encode("utf-8").decode("utf-8")
结果:
问题类似:
Traceback (most recent call last):
File "/usr/local/Cellar/python/3.6.4_4/Frameworks/Python.framework/Versions/3.6/lib/python3.6/logging/__init__.py", line 994, in emit
stream.write(msg)
UnicodeEncodeError: ‘ascii’ codec can’t encode characters in position 152-156: ordinal not in range(128)
貌似出错的position位置变了?
python 3 UnicodeEncodeError: ‘ascii’ codec can’t encode characters in position ordinal not in range(128)
解决Python3下打印utf-8字符串出现UnicodeEncodeError的问题 – 博客 – binsite
此处Python文件最开始已经指明文件编码为utf-8了:
#!/usr/bin/python
# -*- coding: utf-8 -*-
且文件本身的确是utf-8编码:
python(三):Python3—UnicodeEncodeError ‘ascii’ codec can’t encode characters in position 0-1 – CSDN博客
要用到PYTHONIOENCODING?
感觉不太对
Python3 UnicodeEncodeError 问题解决 – CSDN博客
试试:
import sys
import io
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding=’utf-8′)
结果问题依旧。
试试:
CreateTableSqlTemplate = str(“""xxx""")
结果:
问题依旧。
此处,好像是这个中文的逗号:
导致出错的。
-》当然可以直接删除掉,但是不是好的做法。
还是希望此处可以正常输出这个逗号的。
去给PyCharm的debug加上:
PYTHONIOENCODING=utf-8
试试
结果:
没法允许。去加上环境变量中:
问题依旧。
去给filehandler中加上编码
logging.basicConfig(
level = fileLogLevel,
format = fileLogFormat,
datefmt = fileLogDateFormat,
filename = logFilename,
encoding = "utf-8",
filemode = ‘w’)
结果:
ValueError: Unrecognised argument(s): encoding
python 3 logging.basicConfig encoding
Logging HOWTO — Python 3.6.5 documentation
没有提到encoding或encode
python – Add encoding parameter to logging.basicConfig – Stack Overflow
说是不要用basicConfig,换成logging.FileHandler,自己设置文件编码
16.6. logging — Logging facility for Python — Python 3.6.5 documentation
然后试试自己使用fileHandler
rootLogger = logging.getLogger()
rootLogger.setLevel(fileLogLevel)
fileHandler = logging.FileHandler(
filename=logFilename,
mode=’w’,
encoding="utf-8")
fileHandler.setFormatter = logging.Formatter(
fmt=fileLogFormat,
datefmt=fileLogDateFormat
)
rootLogger.addHandler(fileHandler)
结果:
就可以正常打印log了:
【总结】
此处Python3中,对于定义好了的一个字符串:
someStr = """xxx"""
其中xxx中包含了一个中文的逗号,然后去logging去打印日志,然后出错:
UnicodeEncodeError: ‘ascii’ codec can’t encode characters in position 334-338: ordinal not in range(128)
最后确定根本原因是:
初始化logging时,用的是basicConfig,不支持指定文件编码
导致默认fileHandler的文件编码(估计)是ASCII,然后无法输出此处中文字符
解决办法是:
设置logging的fileHandler的(文件的)encoding
具体做法:
rootLogger = logging.getLogger()
rootLogger.setLevel(fileLogLevel)
fileHandler = logging.FileHandler(
filename=logFilename,
mode=’w’,
encoding="utf-8")
fileHandler.setFormatter = logging.Formatter(
fmt=fileLogFormat,
datefmt=fileLogDateFormat
)
rootLogger.addHandler(fileHandler)
然后即可正常输出日志。