5
5
# Useful when logged in over a serial line.
6
6
# Copyright 2013 by Akkana Peck -- share and enjoy under the GPL v2 or later.
7
7
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
+
8
11
import os , sys
9
12
import fcntl
10
13
import posix
@@ -14,34 +17,45 @@ import re
14
17
import termios
15
18
import select
16
19
17
- tty = open ('/dev/tty' , 'r+' )
18
- tty .write ('\033 [7\033 [r\033 [999;999H\033 [6n' )
19
- tty .flush ()
20
-
21
20
fd = sys .stdin .fileno ()
22
21
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 ()
27
31
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 )
30
36
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 )
40
39
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 )))
42
51
43
52
fcntl .ioctl (fd , termios .TIOCSWINSZ ,
44
53
struct .pack ("HHHH" , rows , cols , 0 , 0 ))
45
54
46
- print "\n Reset the terminal to" , rows , "rows" , cols , "cols"
55
+ print ("\n Reset the terminal to %d rows, %d cols" % (rows , cols ))
56
+
57
+
58
+
59
+
60
+
47
61
0 commit comments