Python – how many characters are there in line in a console

pythonshell

How can I find out how may character are there in a line before the end line in an interactive shell using python? (Usually 80)

Best Answer

You can use the tput utility to query the number of lines and columns available in the terminal. You can execute it using subprocess.Popen:

>>> import subprocess
>>> tput = subprocess.Popen(['tput', 'cols'], stdout=subprocess.PIPE)
>>> int(tput.communicate()[0].strip())
180

The same principle can also be applied to query the $COLUMNS variable as mentioned by gregseth:

>>> tput = subprocess.Popen(['echo $COLUMNS'], shell=True, stdout=subprocess.PIPE)
>>> int(tput.communicate()[0].strip())
180

Lastly, if you are OK with using the curses library for such a simple problem, as proposed by Ignacio Vazquez-Abrams, then note that you'll need to perform three statements, not one:

>>> import curses
>>> curses.setupterm()
>>> curses.tigetnum('cols')
180

If the terminal is resized, then setupterm will need to be called before the new terminal width can be queried using tigetnum.