Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how many characters are there in line in a console?

Tags:

python

shell

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)

like image 246
Ruggero Turra Avatar asked Jan 20 '10 21:01

Ruggero Turra


4 Answers

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.

like image 176
Stephan202 Avatar answered Nov 05 '22 16:11

Stephan202


curses.tigetnum('cols')

like image 31
Ignacio Vazquez-Abrams Avatar answered Nov 05 '22 18:11

Ignacio Vazquez-Abrams


I don't know specifically in python,
but in a shell the environment variable $COLUMNS contains the information you want.

like image 36
gregseth Avatar answered Nov 05 '22 18:11

gregseth


Since python3.3 there is another way for querying the size of a terminal.

import os

Width of the terminal window in characters

columns = os.get_terminal_size(0)[0]

Height of the terminal window in character

lines = os.get_terminal_size(0)[1]
like image 2
On4r4p Avatar answered Nov 05 '22 18:11

On4r4p