Skip to content

Commit 8e27c51

Browse files
committed
new version
1 parent 24aa1e5 commit 8e27c51

File tree

1 file changed

+35
-21
lines changed

1 file changed

+35
-21
lines changed

termsize

Lines changed: 35 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,9 @@
55
# Useful when logged in over a serial line.
66
# Copyright 2013 by Akkana Peck -- share and enjoy under the GPL v2 or later.
77

8+
# In the unlikely event you ever need to *set* the terminal size, check out:
9+
# https://github.com/zerorax/pyresize/blob/master/resize.py
10+
811
import os, sys
912
import fcntl
1013
import posix
@@ -14,34 +17,45 @@ import re
1417
import termios
1518
import select
1619

17-
tty = open('/dev/tty', 'r+')
18-
tty.write('\033[7\033[r\033[999;999H\033[6n')
19-
tty.flush()
20-
2120
fd = sys.stdin.fileno()
2221

23-
oldterm = termios.tcgetattr(fd)
24-
newattr = oldterm[:]
25-
newattr[3] = newattr[3] & ~termios.ICANON & ~termios.ECHO
26-
termios.tcsetattr(fd, termios.TCSANOW, newattr)
22+
# python3 has get_terminal size. Yay!
23+
if hasattr(os, 'get_terminal_size'):
24+
cols, rows = os.get_terminal_size()
25+
26+
# python2 does not.
27+
else:
28+
tty = open('/dev/tty', 'r+')
29+
tty.write('\033[7\033[r\033[999;999H\033[6n')
30+
tty.flush()
2731

28-
oldflags = fcntl.fcntl(fd, fcntl.F_GETFL)
29-
fcntl.fcntl(fd, fcntl.F_SETFL, oldflags | os.O_NONBLOCK)
32+
oldterm = termios.tcgetattr(fd)
33+
newattr = oldterm[:]
34+
newattr[3] = newattr[3] & ~termios.ICANON & ~termios.ECHO
35+
termios.tcsetattr(fd, termios.TCSANOW, newattr)
3036

31-
try:
32-
while True:
33-
r, w, e = select.select([fd], [], [])
34-
if r:
35-
output = sys.stdin.read()
36-
break
37-
finally:
38-
termios.tcsetattr(fd, termios.TCSAFLUSH, oldterm)
39-
fcntl.fcntl(fd, fcntl.F_SETFL, oldflags)
37+
oldflags = fcntl.fcntl(fd, fcntl.F_GETFL)
38+
fcntl.fcntl(fd, fcntl.F_SETFL, oldflags | os.O_NONBLOCK)
4039

41-
rows, cols = map(int, re.findall(r'\d+', output))
40+
try:
41+
while True:
42+
r, w, e = select.select([fd], [], [])
43+
if r:
44+
output = sys.stdin.read()
45+
break
46+
finally:
47+
termios.tcsetattr(fd, termios.TCSAFLUSH, oldterm)
48+
fcntl.fcntl(fd, fcntl.F_SETFL, oldflags)
49+
50+
rows, cols = list(map(int, re.findall(r'\d+', output)))
4251

4352
fcntl.ioctl(fd, termios.TIOCSWINSZ,
4453
struct.pack("HHHH", rows, cols, 0, 0))
4554

46-
print "\nReset the terminal to", rows, "rows", cols, "cols"
55+
print("\nReset the terminal to %d rows, %d cols" % (rows, cols))
56+
57+
58+
59+
60+
4761

0 commit comments

Comments
 (0)