Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the amount of available lines in a terminal

How can the amount of available lines in a terminal be found?

Preferably in a cross-platform manner but any suggestions (even OS-specific) are welcome.

The height and length of a terminal can be found using the os module however this does not take into account the amount of lines that may already have been used.

To clarify things here is an example:

In this example the height of the terminal here is 33 however since 3 lines have been used, only 30 lines are available.

like image 972
Xantium Avatar asked Jan 31 '18 18:01

Xantium


People also ask

How to count the number of lines in a text file in terminal?

wc. The wc command is used to find the number of lines, characters, words, and bytes of a file. To find the number of lines using wc, we add the -l option. This will give us the total number of lines and the name of the file.

How many characters are in a terminal line?

The limit of the line length in 70–80 characters may well have originated from various technical limitations of various equipment. The American teletypewriters could type only 72 CPL, while the British ones even less, 70 CPL. In the era of typewriters, most designs of the typewriter carriage were limited to 80–90 CPL.


2 Answers

Determining by that screen shot, you are on Windows

This is from http://code.activestate.com/recipes/440694-determine-size-of-console-window-on-windows/

from ctypes import windll, create_string_buffer

# stdin handle is -10
# stdout handle is -11
# stderr handle is -12

h = windll.kernel32.GetStdHandle(-12)
csbi = create_string_buffer(22)
res = windll.kernel32.GetConsoleScreenBufferInfo(h, csbi)

if res:
    import struct
    (bufx, bufy, curx, cury, wattr,
     left, top, right, bottom, maxx, maxy) = struct.unpack("hhhhHhhhhhh", csbi.raw)
    sizex = right - left + 1
    sizey = bottom - top + 1
else:
    sizex, sizey = 80, 25 # can't determine actual size - return default values

print sizex, sizey, curx, cury

That will give you screen size, and the cursor position.

cury is the line, so you can calculate the number of lines left.

However, you may want to re-check the console window size as you progress, as the user may resize the window at any time.

like image 182
Edwin van Mierlo Avatar answered Oct 17 '22 18:10

Edwin van Mierlo


To determine the terminal size (for any OS platform) -

import os
size = os.get_terminal_size() 
print(size)

The output generated will be : os.terminal_size(columns=80, lines=24) Here columns is the width of the terminal window and lines is the height (80 and 24 is just the reference value). You can use these as print("-"*size.columns) or anything else. I hope this helps!

like image 4
Annie Chakraborty Avatar answered Oct 17 '22 18:10

Annie Chakraborty