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:
%%html
magic to create a canvas and js script.div.CodeMirror-lines
element and get its font and width.measureText
to measure the length of one character.%%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.