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
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]
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
精彩评论