【问题标题】:Inspecting Python object in Pyodide在 Pyodide 中检查 Python 对象
【发布时间】:2019-11-04 00:09:20
【问题描述】:

Pyodide 是相当新的,但我很想知道是否有一种方法可以让用户像使用 Js 对象一样检查 Python 对象。例如,现在如果你 printpyodide 中的一个 dict,输出是一个字符串:

但是如果你console.log一个JavaScript对象,它会输出一些浏览器可以理解的东西,你可以点击展开查看它的属性。

对于调试,我认为这种实用程序是必要的,几乎所有的 IDE 都有它。使用 pyodide 创建一个完整的 Python 环境,我不认为这太难了。

【问题讨论】:

    标签: python pyodide


    【解决方案1】:

    您可以将 python 对象发送到控制台。在python方面你可以做

    pyodide.runPython(`
       myvar = {"msg": "Hello from python"}
       from js import console
       console.log(myvar)
    `);
    

    在javascript方面你可以

    console.log(pyodide.globals.myvar);
    

    基本的 python 类型被转换为它们的 javascript 等价物,并且可以直接检查。其他类型包装在 Proxy 对象中。 chrome devTools 控制台窗口中显示的信息对这些类型不是很有帮助。

    但是 chrome devTools 可以使用这样的自定义格式化程序进行扩展

    (function() {
      var formatter = {
        header: function(x, config) {
          if (config && config.PyProxyFormatter) {
            return ["div", {"width": "100px"}, config.key + ": " + String(x)];
          }
          if (typeof x === 'function' &&
                pyodide._module.PyProxy.isPyProxy(x)) {
            return ["div", {}, String(x)];
          }
          return null;
        },
        hasBody: function(x) {
          return true;
        },
        body: function(x, config) {
          var level = config !== undefined ? config.level : 0;
          if (typeof x === 'function' &&
                pyodide._module.PyProxy.isPyProxy(x)) {
            var keys = pyodide.globals.dir(x);
            var elements = keys.map(function(key) {
              var childObj = x[key];
              var child;
              if (typeof childObj === 'object' ||
                  (typeof childObj === 'function' &&
                   pyodide._module.PyProxy.isPyProxy(childObj))) {
                child = ["object", { 
                   object: childObj, 
                   config: {PyProxyFormatter: true, key: key, level: level + 1}}];
              } else {
                child = key + ": " + String(childObj);
              }
              return ["div", {style: "margin-left: " + level*20 + "px"}, child];
            });
            return ["div", {}].concat(elements);
          } else {
            return ["div", {}, ["object", { object: x}]];
          }
        }
      };
      window.devtoolsFormatters = [formatter];
    }
    )();
    

    【讨论】:

      猜你喜欢
      • 2017-01-08
      • 1970-01-01
      • 2011-11-23
      • 2023-04-09
      • 2022-01-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多