Skip to content

Commit ffa777d

Browse files
committed
Fixed ZeroDivisionError in async_alert() when shutil.get_terminal_size().columns returned 0.
1 parent 4c5bcce commit ffa777d

File tree

4 files changed

+14
-3
lines changed

4 files changed

+14
-3
lines changed

CHANGELOG.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,8 @@
1+
## 2.5.4 (TBD)
2+
* Bug Fixes
3+
* Fixed `ZeroDivisionError` in `async_alert()` when `shutil.get_terminal_size().columns`
4+
returned 0.
5+
16
## 2.5.3 (November 5, 2024)
27
* Enhancements
38
* Changed `CommandSet._cmd` to a read-only property which never returns `None` because it

cmd2/cmd2.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5335,9 +5335,12 @@ def async_alert(self, alert_msg: str, new_prompt: Optional[str] = None) -> None:
53355335
if update_terminal:
53365336
import shutil
53375337

5338+
# Prior to Python 3.11, this can return 0 for things like pseudo terminals.
5339+
terminal_columns = shutil.get_terminal_size().columns or 80
5340+
53385341
# Print a string which replaces the onscreen prompt and input lines with the alert.
53395342
terminal_str = ansi.async_alert_str(
5340-
terminal_columns=shutil.get_terminal_size().columns,
5343+
terminal_columns=terminal_columns,
53415344
prompt=rl_get_display_prompt(),
53425345
line=readline.get_line_buffer(),
53435346
cursor_offset=rl_get_point(),

cmd2/utils.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -874,7 +874,8 @@ def align_text(
874874
)
875875

876876
if width is None:
877-
width = shutil.get_terminal_size().columns
877+
# Prior to Python 3.11, this can return 0 for things like pseudo terminals.
878+
width = shutil.get_terminal_size().columns or 80
878879

879880
if width < 1:
880881
raise ValueError("width must be at least 1")

tests/test_utils.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -624,7 +624,9 @@ def test_align_text_term_width():
624624
text = 'foo'
625625
fill_char = ' '
626626

627-
term_width = shutil.get_terminal_size().columns
627+
# Prior to Python 3.11, this can return 0 for things like pseudo terminals.
628+
# So copy the behavior of cu.align_text() and fall back to 80 if needed.
629+
term_width = shutil.get_terminal_size().columns or 80
628630
expected_fill = (term_width - ansi.style_aware_wcswidth(text)) * fill_char
629631

630632
aligned = cu.align_text(text, cu.TextAlignment.LEFT, fill_char=fill_char)

0 commit comments

Comments
 (0)