检测jupyter笔记本中的线宽?

2024-04-27 02:54:52 发布

您现在位置:Python中文网/ 问答频道 /正文

对于ipython,我使用它来检测控制台线宽:

    ncols =  int(os.getenv('COLUMNS', 80))

如何从python对jupyter笔记本执行相同的操作


Tags: columnsosipython笔记本jupytergetenvintncols
1条回答
网友
1楼 · 发布于 2024-04-27 02:54:52

jupyter单元格的宽度可以从笔记本的样式中检索。您可以使用浏览器的开发工具来检查html,也可以使用笔记本单元格中的以下代码来检索单元格行的宽度,然后计算它将容纳的字符数

以下将:

  • 使用%%htmlmagic创建画布和js脚本
  • 查找div.CodeMirror-lines元素并获取其字体和宽度
  • 将画布设置为与单元格的line元素相同的字体
  • 使用measureText测量一个字符的长度
  • 提醒您适合于该行宽度的字符数
%%html
<canvas id="canvas"></canvas>
<script>
    // retrieve the width and font
    var el = document.querySelector("div.CodeMirror-lines")
    var ff = window.getComputedStyle(el, null).getPropertyValue('font');
    var widthpxl = el.clientWidth

    //set up canvas to measure text width
    var can = document.getElementById('canvas');
    var ctx = can.getContext('2d');
    ctx.font = ff;

    //measure one char of text and compute num char in one line
    var txt = ctx.measureText('A');
    alert(Math.floor(widthpxl/txt.width))
    //EDIT: to populate python variable with the output:
    IPython.notebook.kernel.execute("ncols=" + Math.floor(widthpxl/txt.width));
</script>

相关问题 更多 >