简体   繁体   中英

Detect line width in jupyter notebook?

For ipython I use this to detect console line width:

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

how do I do the same for jupyter notebook from python?

The width of a jupyter cell can be retrieved from the notebook's style. You can use the browser's development tools to inspect the html or you could use the following code in a notebook cell to retrieve the width of a cell line and then calculate the number of characters it will hold.

The following will:

  • Use %%html magic to create a canvas and js script.
  • look up the div.CodeMirror-lines element and get its font and width.
  • set the canvas to the same font as the cell's line element.
  • use measureText to measure the length of one character.
  • alert you of the number of characters that will fit within the line's width.
%%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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM