【问题标题】:Not able to explore json.loads() code with pdb无法使用 pdb 探索 json.loads() 代码
【发布时间】:2019-01-11 11:33:33
【问题描述】:

我想看看当我使用 json.loads() 将 json 字符串转换为 python 字典时正在执行什么代码

例如

import json  
s = '{"a": 1, "b": 2}'  # input json string
d = json.loads(s)  # output dictionary object 

我试图通过调试代码并达到核心逻辑和解析来了解内部逻辑。

import json  
s = '{"a": 1, "b": 2}'  # input json string
import pdb; pdb.set_trace()
d = json.loads(s)  # output dictionary object 

通过进入d = json.loads(s),我可以访问json/init.py 中的loads()

这进一步带我进入decode(),然后进入json/decoder.pyJSONDecoder 类中的raw_decode() 方法@

def raw_decode(self, s, idx=0):
        """Decode a JSON document from ``s`` (a ``str`` beginning with
        a JSON document) and return a 2-tuple of the Python
        representation and the index in ``s`` where the document ended.
        This can be used to decode a JSON document from a string that may
        have extraneous data at the end.
        """
        try:
            obj, end = self.scan_once(s, idx)
        except StopIteration as err:
            raise JSONDecodeError("Expecting value", s, err.value) from None
        return obj, end

raw_decode() 我无法进一步进入obj, end = self.scan_once(s, idx) pdd 将我发送到最后一行return obj, end

(Pdb) l
350             This can be used to decode a JSON document from a string that may
351             have extraneous data at the end.
352     
353             """
354             try:
355  ->             obj, end = self.scan_once(s, idx)
356             except StopIteration as err:
357                 raise JSONDecodeError("Expecting value", s, err.value) from None
358             return obj, end
[EOF]
(Pdb) s
> /usr/lib/python3.6/json/decoder.py(358)raw_decode()
-> return obj, end
(Pdb) 

我想查看内部代码,并且我希望使用 pdb 访问该代码,因为我期望通过进入 pdb 将进入内部代码。
我什至无法在json/scanner.py_json 模块中访问make_scanner = c_make_scanner or py_make_scanner

如何使用调试实现核心迭代和解析逻辑?

【问题讨论】:

  • d 在 pdb 中保留。为变量使用不同的名称。超过两个字符的内容。

标签: python json debugging pdb


【解决方案1】:

我相信这是因为 Python 使用的是原生版本的 JSON 扫描器,所以您不能使用 Python 调试器。见json/scanner.py

try:
    from _json import make_scanner as c_make_scanner
except ImportError:
    c_make_scanner = None

如果 C/native 版本不可用,则使用 Python 编写的备用版本(也在上面链接的文件中定义)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-06-26
    • 2020-06-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多