最新消息:20210917 已从crifan.com换到crifan.org

【已解决】python3.9报错:TypeError __init__ got an unexpected keyword argument encoding

Python crifan 8021浏览 0评论
自己的gitbook的template,之前正常运行没问题。
现在运行报错:
rm -f book.json
Traceback (most recent call last):
  File "/Users/crifan/dev/dev_root/gitbook/GitbookTemplate/gitbook_template/common/tools/generate_book_json.py", line 178, in <module>
    templateJson = json.load(templateJsonFp, encoding="utf-8")
  File "/Users/crifan/.pyenv/versions/3.9.4/lib/python3.9/json/__init__.py", line 293, in load
    return loads(fp.read(),
  File "/Users/crifan/.pyenv/versions/3.9.4/lib/python3.9/json/__init__.py", line 359, in loads
    return cls(**kw).decode(s)
TypeError: __init__() got an unexpected keyword argument 'encoding'
make: *** [../../common/gitbook_makefile.mk:292: generate_book_json] Error 1
去看了下,源码是:
common/tools/generate_book_json.py
templateJson = json.load(templateJsonFp, encoding="utf-8")
-》很是奇怪,为何会报错encoding多出参数?
难道是新版9.4的Python,不需要encoding了?
去找找看看
python 3.9 TypeError __init__ got an unexpected keyword argument encoding
VirtualCodebase fails with Python 3.9 · Issue #6 · nexB/commoncode (github.com)
The json.load call in VirtualCodebase._get_scan_data_helper provide a encoding=’utf-8′ argument that was removed in Python 3.9.
还真是
Python not decoding JSON because “encoding” is an unexpected argument – Stack Overflow
json — JSON encoder and decoder — Python 3.9.5 documentation
Changed in version 3.9: The keyword argument encoding has been removed.
找找看,为何被移除
python 3.9 json.load encoding removed
issue 39377: json.loads encoding parameter deprecation removal in Python 3.9 – Python tracker
This is a followup of issue33461. The warning says about removal of the encoding parameter in 3.9 . It’s already ignored since 3.1 hence I assume this should be raising a TypeError in 3.9 removing the deprecation warning.
意思是:自从Python 3.1,其实json.load的encoding早就被移除了?
不管如何,看起来是,从:2020-01-20,早就移除掉了
Why was the keyword argument ‘encoding’ removed from json.loads() in Python 3.9? – Stack Overflow
python内部自动检测编码方式,无需encoding了
具体实现逻辑:
https://github.com/python/cpython/blob/12d0a7642fc552fa17b1608fe135306cddec5f4e/Lib/json/__init__.py#L341
def loads(s, *, cls=None, object_hook=None, parse_float=None,
        parse_int=None, parse_constant=None, object_pairs_hook=None, **kw):
。。。
        s = s.decode(detect_encoding(s), 'surrogatepass')
Encoding parameter to json.loads is deprecated and will be removed in Python 3.9 · Issue #5165 · jupyter/notebook (github.com)
【总结】】
Python 3.9之后,去掉了json.load的encoding参数
原因:内部可以自动判断文件编码,无需encoding
此处解决办法:直接去掉encoding参数:
templateJson = json.load(templateJsonFp)
即可

转载请注明:在路上 » 【已解决】python3.9报错:TypeError __init__ got an unexpected keyword argument encoding

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
99 queries in 0.428 seconds, using 23.44MB memory