检测jupyter笔记本中的线宽?

时间:2020-05-27 20:56:57

标签: python jupyter-notebook jupyter jupyter-lab

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

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

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

1 个答案:

答案 0 :(得分:1)

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

以下内容将

  • 使用%%html魔术来创建画布和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>
相关问题