Skip to content

Commit 483f31d

Browse files
committed
Use portable library functions in getscrwidth()
Since Python 3.3 the library function os.get_terminal_size() is available, which is more portable and makes directly using ioctl unnecessary. We explicitly do not use shutil.get_terminal_size() to preserve the current logic and avoid using sys.__stdout__ which makes testing harder.
1 parent 79c075f commit 483f31d

File tree

1 file changed

+10
-17
lines changed

1 file changed

+10
-17
lines changed

lib/cfv/term.py

Lines changed: 10 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,27 +1,20 @@
11
import os
2-
import struct
32
import sys
43

54

65
def getscrwidth():
7-
w = -1
8-
try:
9-
from fcntl import ioctl
6+
tty = sys.stdin.isatty() and sys.stdin or sys.stdout.isatty() and sys.stdout or sys.stderr.isatty() and sys.stderr or None
7+
if tty:
108
try:
11-
from termios import TIOCGWINSZ
12-
except ImportError:
13-
from TERMIOS import TIOCGWINSZ
14-
tty = sys.stdin.isatty() and sys.stdin or sys.stdout.isatty() and sys.stdout or sys.stderr.isatty() and sys.stderr or None
15-
if tty:
16-
h, w, _, _ = struct.unpack('hhhh', ioctl(tty.fileno(), TIOCGWINSZ, '\0' * struct.calcsize('hhhh')))
17-
except ImportError:
18-
pass
19-
if w > 0:
20-
return w
21-
c = os.environ.get('COLUMNS', 80)
9+
termsize = os.get_terminal_size(tty.fileno())
10+
if termsize.columns > 0:
11+
return termsize.columns
12+
except (AttributeError, ValueError, OSError):
13+
pass
14+
2215
try:
23-
return int(c)
24-
except ValueError:
16+
return int(os.environ['COLUMNS'])
17+
except (KeyError, ValueError):
2518
return 80
2619

2720

0 commit comments

Comments
 (0)