代码之家  ›  专栏  ›  技术社区  ›  Alok

无法使用pdb探索json.loads()代码

  •  0
  • Alok  · 技术社区  · 6 年前

    我想看看当我使用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) 我能够到 loads() 出席 json/ init .py

    让我更深入地了解 decode() 然后 raw_decode() 方法存在于 JSONDecoder 上课 json/decoder.py

    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
    

    原始解码() 我无法进一步深入 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 将进入内部代码。
    我连 make_scanner = c_make_scanner or py_make_scanner 在里面 json/scanner.py _json 模块。

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

    1 回复  |  直到 6 年前
        1
  •  2
  •   Aurel Bílý    6 年前

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

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

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