【发布时间】:2023-03-16 14:48:01
【问题描述】:
对于 ipython,我使用它来检测控制台线宽:
ncols = int(os.getenv('COLUMNS', 80))
如何从 python 中为 jupyter notebook 做同样的事情?
【问题讨论】:
标签: python jupyter-notebook jupyter jupyter-lab
对于 ipython,我使用它来检测控制台线宽:
ncols = int(os.getenv('COLUMNS', 80))
如何从 python 中为 jupyter notebook 做同样的事情?
【问题讨论】:
标签: python jupyter-notebook jupyter jupyter-lab
可以从笔记本的样式中检索 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>
【讨论】:
alert(Math.floor(widthpxl/txt.width))替换为IPython.notebook.kernel.execute("ncols=" + Math.floor(widthpxl/txt.width));