【问题标题】:Detect line width in jupyter notebook?检测jupyter笔记本中的线宽?
【发布时间】:2023-03-16 14:48:01
【问题描述】:

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

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

如何从 python 中为 jupyter notebook 做同样的事情?

【问题讨论】:

    标签: python jupyter-notebook jupyter jupyter-lab


    【解决方案1】:

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

    以下将:

    • 使用%%html 魔法创建画布和js 脚本。
    • 查找div.CodeMirror-lines 元素并获取其字体和宽度。
    • 将画布设置为与单元格的线条元素相同的字体。
    • 使用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>
    

    【讨论】:

    • 聪明,谢谢,但我需要从 python 中获取“终端宽度”,而不是从 js ;(
    • 要将其作为python变量获取,您可以将alert(Math.floor(widthpxl/txt.width))替换为IPython.notebook.kernel.execute("ncols=" + Math.floor(widthpxl/txt.width));
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-01
    • 1970-01-01
    • 2017-10-10
    • 1970-01-01
    相关资源
    最近更新 更多