0

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.

  • Does this answer your question? [Python control output positions in terminal/console](https://stackoverflow.com/questions/38264588/python-control-output-positions-in-terminal-console) – mkrieger1 Mar 13 '23 at 09:28
  • 1
    By "raise", to you mean "return", or "increase"? – mkrieger1 Mar 13 '23 at 09:29
  • Also, are you using a library for parsing command-line arguments (like `argparse` from the standard library)? Possibly it can already handle creating and formatting a help page for you. – mkrieger1 Mar 13 '23 at 09:30
  • @mkrieger1 yeah exactly, I wanna have an returned integer to have the number of columns. I'll take a look at what you've given to me. – minimus_maximus Mar 13 '23 at 09:33
  • @mkrieger1 the first proposition only controls the lines (not the columns) and renders the string at the bottom. It's indeed pretty similar to what I need, except I wanna write my string at the right of my terminal, not the bottom. – minimus_maximus Mar 13 '23 at 09:47

1 Answers1

0

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