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)
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
.
curses.tigetnum('cols')
I don't know specifically in python
,
but in a shell the environment variable $COLUMNS
contains the information you want.
Since python3.3 there is another way for querying the size of a terminal.
import os
columns = os.get_terminal_size(0)[0]
lines = os.get_terminal_size(0)[1]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With