python3 unicode字符串_【已解决】Python3中如何声明字符串是unicode类型以避免log日志打印出错...
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 ‘經(jīng)銷(xiāo)商參考價(jià)’,
`msrpPrice` int(11) unsigned NOT NULL DEFAULT ‘0’ COMMENT ‘廠(chǎng)商指導(dǎo)價(jià)’,
`mainBrand` char(20) NOT NULL DEFAULT ” COMMENT ‘品牌’,
`subBrand` varchar(20) NOT NULL DEFAULT ” COMMENT ‘子品牌’,
`brandSerie` varchar(20) NOT NULL DEFAULT ” COMMENT ‘車(chē)系’,
`brandSerieId` varchar(15) NOT NULL DEFAULT ” COMMENT ‘車(chē)系ID’,
`model` varchar(50) NOT NULL DEFAULT ” COMMENT ‘車(chē)型’,
`modelId` varchar(15) NOT NULL DEFAULT ” COMMENT ‘車(chē)型ID’,
`modelStatus` char(5) NOT NULL DEFAULT ” COMMENT ‘車(chē)型狀態(tài)’,
`url` varchar(200) NOT NULL DEFAULT ” COMMENT ‘車(chē)型url’,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;"""
logging.info("config=%s, needCreateTable=%s, tableName=%s, createTableSqlTemplate=%s",
config, needCreateTable, tableName, createTableSqlTemplate)
結(jié)果出錯(cuò):
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: ‘a(chǎn)scii’ codec can’t encode characters in position 334-338: ordinal not in range(128)
然后
試了試:
logging.info("createTableSqlTemplate=%s", createTableSqlTemplate.encode("utf-8"))
結(jié)果:
createTableSqlTemplate=b"CREATE TABLE IF NOT EXISTS `%s` (….
輸出了bytes,是不會(huì)出錯(cuò),但是輸出到都是\xxxx,不方便查看原始內(nèi)容了。
然后也試了試加u前綴:
CreateTableSqlTemplate = u"""CREATE TABLE IF NOT EXISTS `%s` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT COMMENT ‘自增,主鍵’。。。。"""
問(wèn)題依舊。
所以想要搞清楚Python3中,如何聲明是unicode字符串
python 3 unicode string
python 3 declare unicode string
試試:
logging.info("createTableSqlTemplate=%s", str(createTableSqlTemplate))
結(jié)果問(wèn)題依舊。
試試:
CreateTableSqlTemplate = b”""xxx""".decode("utf-8")
結(jié)果:
SyntaxError: bytes can only contain ASCII literal characters.
試試:
CreateTableSqlTemplate =?“""xxx""".encode("utf-8").decode("utf-8")
結(jié)果:
問(wèn)題類(lèi)似:
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: ‘a(chǎn)scii’ codec can’t encode characters in position 152-156: ordinal not in range(128)
貌似出錯(cuò)的position位置變了?
python 3??UnicodeEncodeError: ‘a(chǎn)scii’ codec can’t encode characters in position??ordinal not in range(128)
此處Python文件最開(kāi)始已經(jīng)指明文件編碼為utf-8了:
#!/usr/bin/python
# -*- coding: utf-8 -*-
且文件本身的確是utf-8編碼:
要用到PYTHONIOENCODING?
感覺(jué)不太對(duì)
試試:
import sys
import io
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding=’utf-8′)
結(jié)果問(wèn)題依舊。
試試:
CreateTableSqlTemplate = str(“""xxx""")
結(jié)果:
問(wèn)題依舊。
此處,好像是這個(gè)中文的逗號(hào):
導(dǎo)致出錯(cuò)的。
-》當(dāng)然可以直接刪除掉,但是不是好的做法。
還是希望此處可以正常輸出這個(gè)逗號(hào)的。
去給PyCharm的debug加上:
PYTHONIOENCODING=utf-8
試試
結(jié)果:
沒(méi)法允許。去加上環(huán)境變量中:
問(wèn)題依舊。
去給filehandler中加上編碼
logging.basicConfig(
level????= fileLogLevel,
format???= fileLogFormat,
datefmt??= fileLogDateFormat,
filename = logFilename,
encoding = "utf-8",
filemode = ‘w’)
結(jié)果:
ValueError: Unrecognised argument(s): encoding
python 3 logging.basicConfig encoding
沒(méi)有提到encoding或encode
說(shuō)是不要用basicConfig,換成logging.FileHandler,自己設(shè)置文件編碼
然后試試自己使用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)
結(jié)果:
就可以正常打印log了:
【總結(jié)】
此處Python3中,對(duì)于定義好了的一個(gè)字符串:
someStr = """xxx"""
其中xxx中包含了一個(gè)中文的逗號(hào),然后去logging去打印日志,然后出錯(cuò):
UnicodeEncodeError: ‘a(chǎn)scii’ codec can’t encode characters in position 334-338: ordinal not in range(128)
最后確定根本原因是:
初始化logging時(shí),用的是basicConfig,不支持指定文件編碼
導(dǎo)致默認(rèn)fileHandler的文件編碼(估計(jì))是ASCII,然后無(wú)法輸出此處中文字符
解決辦法是:
設(shè)置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)
然后即可正常輸出日志。
總結(jié)
以上是生活随笔為你收集整理的python3 unicode字符串_【已解决】Python3中如何声明字符串是unicode类型以避免log日志打印出错...的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 【区块链】量子链命令行qtum-cli全
- 下一篇: python中superclass是什么