tags:

views:

101

answers:

4

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)

+3  A: 

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

gregseth
+3  A: 

curses.tigetnum('cols')

Ignacio Vazquez-Abrams
First execute `import curses` and then `curses.setupterm()` before you do this.
Stephan202
See also `curses.wrapper`: http://docs.python.org/3.1/library/curses.html#module-curses.wrapper
Dennis Williamson
+2  A: 

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.

Stephan202
A: 

on *nix only

>>> import sys,struct,fnctl,termios
>>> fd = sys.stdin.fileno()
>>> s = struct.pack("HH", 0,0)
>>> size=fcntl.ioctl(fd, termios.TIOCGWINSZ,s)
>>> struct.unpack("HH", size)[-1]
157
ghostdog74
I have used this in the past, and it still makes no sense to me.
jathanism