[Python-checkins] bpo-13041: Use shutil.get_terminal_size() in argparse.HelpFormatter (GH-8459)

Berker Peksag webhook-mailer at python.org
Wed Jul 25 11:23:48 EDT 2018


https://github.com/python/cpython/commit/74102c9a5f2327c4fc47feefa072854a53551d1f
commit: 74102c9a5f2327c4fc47feefa072854a53551d1f
branch: master
author: Berker Peksag <berker.peksag at gmail.com>
committer: GitHub <noreply at github.com>
date: 2018-07-25T18:23:44+03:00
summary:

bpo-13041: Use shutil.get_terminal_size() in argparse.HelpFormatter (GH-8459)

files:
A Misc/NEWS.d/next/Library/2018-07-25-12-08-48.bpo-13041.lNmgDz.rst
M Lib/argparse.py
M Lib/test/test_argparse.py

diff --git a/Lib/argparse.py b/Lib/argparse.py
index a03074924762..83f47e35a73c 100644
--- a/Lib/argparse.py
+++ b/Lib/argparse.py
@@ -85,6 +85,7 @@
 
 import os as _os
 import re as _re
+import shutil as _shutil
 import sys as _sys
 
 from gettext import gettext as _, ngettext
@@ -164,10 +165,7 @@ def __init__(self,
 
         # default setting for width
         if width is None:
-            try:
-                width = int(_os.environ['COLUMNS'])
-            except (KeyError, ValueError):
-                width = 80
+            width = _shutil.get_terminal_size().columns
             width -= 2
 
         self._prog = prog
diff --git a/Lib/test/test_argparse.py b/Lib/test/test_argparse.py
index 85449c729902..f0802a509731 100644
--- a/Lib/test/test_argparse.py
+++ b/Lib/test/test_argparse.py
@@ -23,9 +23,9 @@ class TestCase(unittest.TestCase):
     def setUp(self):
         # The tests assume that line wrapping occurs at 80 columns, but this
         # behaviour can be overridden by setting the COLUMNS environment
-        # variable.  To ensure that this assumption is true, unset COLUMNS.
+        # variable.  To ensure that this width is used, set COLUMNS to 80.
         env = support.EnvironmentVarGuard()
-        env.unset("COLUMNS")
+        env['COLUMNS'] = '80'
         self.addCleanup(env.__exit__)
 
 
@@ -5122,6 +5122,7 @@ def test_all_exports_everything_but_modules(self):
 class TestWrappingMetavar(TestCase):
 
     def setUp(self):
+        super().setUp()
         self.parser = ErrorRaisingArgumentParser(
             'this_is_spammy_prog_with_a_long_name_sorry_about_the_name'
         )
diff --git a/Misc/NEWS.d/next/Library/2018-07-25-12-08-48.bpo-13041.lNmgDz.rst b/Misc/NEWS.d/next/Library/2018-07-25-12-08-48.bpo-13041.lNmgDz.rst
new file mode 100644
index 000000000000..d0871a8ef1d6
--- /dev/null
+++ b/Misc/NEWS.d/next/Library/2018-07-25-12-08-48.bpo-13041.lNmgDz.rst
@@ -0,0 +1,3 @@
+Use :func:`shutil.get_terminal_size` to calculate the terminal width
+correctly in the ``argparse.HelpFormatter`` class.  Initial patch by Zbyszek
+Jędrzejewski-Szmek.



More information about the Python-checkins mailing list