Write a specific string in the middle and the end of a terminal no matter its width (find terminal width)

Question:

I’m working on a python app and try to write the -help page of the script to show all its actions on the terminal when calling it with thie -h or -help option. The head should look something like this :

==================================== help page ====================================

However, I find myself unable to do that because I don’t have control of the terminal width, so I can’t predict the number of ‘=’ characters to put between these words to make the rendered line symmetrical.So I wanna know if there is a way to pick the size of the terminal screen, then adjust the number of spaces based on that size.

I tried looking for functions that raise the terminal size but didn’t find any.

Asked By: minimus_maximus

||

Answers:

Found the solution for those who need it :

Simply use the os.get_terminal_size() function. The substracted 5 and 6 depends on what you write in the middle. For me it is ‘help page’, so 9 characters plusone space on both sides, so a total of 11 (5+6) to be aproximatly symmetrical. But if the total width is odd, it’s 5 on both left and right variables.

import os
import sys

def terminal():

    size = os.get_terminal_size()
    width = size.columns
    
    if width % 2 == 0:
        left = width // 2 - 6
        right= width // 2 - 5
    elif width % 2 == 1:
        left = right = width // 2 - 5

    try:
        if '-h' in sys.argv or '-help' in sys.argv:
            print(left*'=','help page',right*'=')

Which gives something like this (based on your terminal width):

==================================== help page ====================================

Feel free to replace the ‘=’ character with whatever you want.

Hope it helps

Answered By: minimus_maximus
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.