[英]Inspecting Python object in Pyodide
Pyodide很新,但我很想知道是否有辦法讓用戶檢查 Python 對象,就像他們可以使用 Js 對象一樣。 例如,現在如果您在 pyodide 中print
dict,則 output 是一個字符串:
但是如果你console.log
一個 JavaScript object,它會輸出一些瀏覽器可以理解的內容,你可以點擊展開查看它的屬性。
對於調試,我認為這種實用程序是必要的,幾乎所有的 IDE 都有它。 使用 pyodide 創建一個完整的 Python 環境,我不認為這太難了。
您可以將 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 object 中。 chrome devTools 控制台 window 中顯示的信息對這些類型不是很有幫助。
但是 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];
}
)();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.