Skip to content

Commit 5ba9a91

Browse files
gh-66436: Improved prog default value for argparse.ArgumentParser
It can now have one of three forms: * basename(argv0) -- for simple scripts * python arv0 -- for directories, ZIP files, etc * python -m module -- for imported modules
1 parent 6f4d64b commit 5ba9a91

File tree

6 files changed

+160
-16
lines changed

6 files changed

+160
-16
lines changed

Doc/library/argparse.rst

Lines changed: 31 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ Quick Links for ArgumentParser
3030
========================= =========================================================================================================== ==================================================================================
3131
Name Description Values
3232
========================= =========================================================================================================== ==================================================================================
33-
prog_ The name of the program Defaults to ``os.path.basename(sys.argv[0])``
33+
prog_ The name of the program
3434
usage_ The string describing the program usage
3535
description_ A brief description of what the program does
3636
epilog_ Additional description of the program after the argument help
@@ -214,8 +214,8 @@ ArgumentParser objects
214214
as keyword arguments. Each parameter has its own more detailed description
215215
below, but in short they are:
216216

217-
* prog_ - The name of the program (default:
218-
``os.path.basename(sys.argv[0])``)
217+
* prog_ - The name of the program (default: generated from the ``__main__``
218+
module attributes and ``sys.argv[0]``)
219219

220220
* usage_ - The string describing the program usage (default: generated from
221221
arguments added to parser)
@@ -268,10 +268,18 @@ The following sections describe how each of these are used.
268268
prog
269269
^^^^
270270

271-
By default, :class:`ArgumentParser` objects use the base name
272-
(see :func:`os.path.basename`) of ``sys.argv[0]`` to determine
273-
how to display the name of the program in help messages. This default is almost
274-
always desirable because it will make the help messages match the name that was
271+
By default, :class:`ArgumentParser` calculates the name of the program
272+
to display in help messages depending on the way the Python inerpreter was run:
273+
274+
* The :func:`base name <os.path.basename>` of ``sys.argv[0]`` if a file was
275+
passed as argument.
276+
* The Python inerpreter name followed by ``sys.argv[0]`` if a directory or
277+
a zipfile was passed as argument.
278+
* The Python inerpreter name followed by ``-m`` followed by the
279+
module or package name if the :option:`-m` option was used.
280+
281+
This default is almost
282+
always desirable because it will make the help messages match the string that was
275283
used to invoke the program on the command line. For example, consider a file
276284
named ``myprogram.py`` with the following code::
277285

@@ -281,7 +289,7 @@ named ``myprogram.py`` with the following code::
281289
args = parser.parse_args()
282290

283291
The help for this program will display ``myprogram.py`` as the program name
284-
(regardless of where the program was invoked from):
292+
(regardless of where the program was invoked from) if run it as a script:
285293

286294
.. code-block:: shell-session
287295
@@ -299,6 +307,17 @@ The help for this program will display ``myprogram.py`` as the program name
299307
-h, --help show this help message and exit
300308
--foo FOO foo help
301309
310+
If import it as a module, the help will display a corresponding command line:
311+
312+
.. code-block:: shell-session
313+
314+
$ /usr/bin/python3 -m subdir.myprogram --help
315+
usage: python3 -m subdir.myprogram [-h] [--foo FOO]
316+
317+
options:
318+
-h, --help show this help message and exit
319+
--foo FOO foo help
320+
302321
To change this default behavior, another value can be supplied using the
303322
``prog=`` argument to :class:`ArgumentParser`::
304323

@@ -309,7 +328,8 @@ To change this default behavior, another value can be supplied using the
309328
options:
310329
-h, --help show this help message and exit
311330

312-
Note that the program name, whether determined from ``sys.argv[0]`` or from the
331+
Note that the program name, whether determined from ``sys.argv[0]``,
332+
from the ``__main__`` module attributes or from the
313333
``prog=`` argument, is available to help messages using the ``%(prog)s`` format
314334
specifier.
315335

@@ -324,6 +344,8 @@ specifier.
324344
-h, --help show this help message and exit
325345
--foo FOO foo of the myprogram program
326346

347+
.. versionchanged:: 3.14
348+
The default value is now not simply ``os.path.basename(sys.argv[0])``.
327349

328350
usage
329351
^^^^^

Doc/whatsnew/3.14.rst

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -202,6 +202,13 @@ New Modules
202202
Improved Modules
203203
================
204204

205+
argparse
206+
--------
207+
208+
* The default value of the :ref:`program name <prog>` for
209+
:class:`argparse.ArgumentParser` depends now on the way the Python
210+
interpreter was run.
211+
(Contributed by Serhiy Storchaka and Alyssa Coghlan in :gh:`66436`.)
205212

206213
ast
207214
---

Lib/argparse.py

Lines changed: 16 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1697,6 +1697,21 @@ def add_mutually_exclusive_group(self, *args, **kwargs):
16971697
return super().add_mutually_exclusive_group(*args, **kwargs)
16981698

16991699

1700+
def _prog_name(prog=None):
1701+
if prog is not None:
1702+
return prog
1703+
arg0 = _sys.argv[0]
1704+
mod = _sys.modules['__main__']
1705+
modspec = mod.__spec__
1706+
if modspec is None:
1707+
return _os.path.basename(arg0)
1708+
py = _os.path.basename(_sys.executable)
1709+
if (modspec.name == '__main__' and not modspec.parent and modspec.has_location
1710+
and _os.path.dirname(modspec.origin) == _os.path.join(_os.getcwd(), arg0)):
1711+
return f'{py} {arg0}'
1712+
return f'{py} -m {modspec.name.removesuffix(".__main__")}'
1713+
1714+
17001715
class ArgumentParser(_AttributeHolder, _ActionsContainer):
17011716
"""Object for parsing command line strings into Python objects.
17021717
@@ -1740,11 +1755,7 @@ def __init__(self,
17401755
argument_default=argument_default,
17411756
conflict_handler=conflict_handler)
17421757

1743-
# default setting for prog
1744-
if prog is None:
1745-
prog = _os.path.basename(_sys.argv[0])
1746-
1747-
self.prog = prog
1758+
self.prog = _prog_name(prog)
17481759
self.usage = usage
17491760
self.epilog = epilog
17501761
self.formatter_class = formatter_class

Lib/test/support/import_helper.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -59,7 +59,7 @@ def make_legacy_pyc(source):
5959
"""
6060
pyc_file = importlib.util.cache_from_source(source)
6161
up_one = os.path.dirname(os.path.abspath(source))
62-
legacy_pyc = os.path.join(up_one, source + 'c')
62+
legacy_pyc = os.path.join(up_one, os.path.basename(source) + 'c')
6363
shutil.move(pyc_file, legacy_pyc)
6464
return legacy_pyc
6565

Lib/test/test_argparse.py

Lines changed: 101 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
import io
77
import operator
88
import os
9+
import py_compile
910
import shutil
1011
import stat
1112
import sys
@@ -15,10 +16,16 @@
1516
import argparse
1617
import warnings
1718

18-
from test.support import os_helper, captured_stderr
19+
from test.support import captured_stderr
20+
from test.support import import_helper
21+
from test.support import os_helper
22+
from test.support import script_helper
1923
from unittest import mock
2024

2125

26+
py = os.path.basename(sys.executable)
27+
28+
2229
class StdIOBuffer(io.TextIOWrapper):
2330
'''Replacement for writable io.StringIO that behaves more like real file
2431
@@ -6561,6 +6568,99 @@ def test_os_error(self):
65616568
self.parser.parse_args, ['@no-such-file'])
65626569

65636570

6571+
class TestProgName(TestCase):
6572+
source = textwrap.dedent('''\
6573+
import argparse
6574+
parser = argparse.ArgumentParser()
6575+
parser.parse_args()
6576+
''')
6577+
6578+
def setUp(self):
6579+
self.dirname = 'package' + os_helper.FS_NONASCII
6580+
self.addCleanup(os_helper.rmtree, self.dirname)
6581+
os.mkdir(self.dirname)
6582+
6583+
def make_script(self, dirname, basename, *, compiled=False):
6584+
script_name = script_helper.make_script(dirname, basename, self.source)
6585+
if not compiled:
6586+
return script_name
6587+
py_compile.compile(script_name, doraise=True)
6588+
os.remove(script_name)
6589+
pyc_file = import_helper.make_legacy_pyc(script_name)
6590+
return pyc_file
6591+
6592+
def make_zip_script(self, script_name, name_in_zip=None):
6593+
zip_name, _ = script_helper.make_zip_script(self.dirname, 'test_zip',
6594+
script_name, name_in_zip)
6595+
return zip_name
6596+
6597+
def check_usage(self, expected, *args, **kwargs):
6598+
res = script_helper.assert_python_ok(*args, '-h', **kwargs)
6599+
self.assertEqual(os.fsdecode(res.out.splitlines()[0]),
6600+
f'usage: {expected} [-h]')
6601+
6602+
def test_script(self, compiled=False):
6603+
basename = os_helper.TESTFN
6604+
script_name = self.make_script(self.dirname, basename, compiled=compiled)
6605+
self.check_usage(os.path.basename(script_name), script_name, '-h')
6606+
6607+
def test_script_compiled(self):
6608+
self.test_script(compiled=True)
6609+
6610+
def test_directory(self, compiled=False):
6611+
dirname = os.path.join(self.dirname, os_helper.TESTFN)
6612+
os.mkdir(dirname)
6613+
self.make_script(dirname, '__main__', compiled=compiled)
6614+
self.check_usage(f'{py} {dirname}', dirname)
6615+
dirname2 = os.path.join(os.curdir, dirname)
6616+
self.check_usage(f'{py} {dirname2}', dirname2)
6617+
6618+
def test_directory_compiled(self):
6619+
self.test_directory(compiled=True)
6620+
6621+
def test_module(self, compiled=False):
6622+
basename = 'module' + os_helper.FS_NONASCII
6623+
modulename = f'{self.dirname}.{basename}'
6624+
self.make_script(self.dirname, basename, compiled=compiled)
6625+
self.check_usage(f'{py} -m {modulename}',
6626+
'-m', modulename, PYTHONPATH=os.curdir)
6627+
6628+
def test_module_compiled(self):
6629+
self.test_module(compiled=True)
6630+
6631+
def test_package(self, compiled=False):
6632+
basename = 'subpackage' + os_helper.FS_NONASCII
6633+
packagename = f'{self.dirname}.{basename}'
6634+
subdirname = os.path.join(self.dirname, basename)
6635+
os.mkdir(subdirname)
6636+
self.make_script(subdirname, '__main__', compiled=compiled)
6637+
self.check_usage(f'{py} -m {packagename}',
6638+
'-m', packagename, PYTHONPATH=os.curdir)
6639+
self.check_usage(f'{py} -m {packagename}',
6640+
'-m', packagename + '.__main__', PYTHONPATH=os.curdir)
6641+
6642+
def test_package_compiled(self):
6643+
self.test_package(compiled=True)
6644+
6645+
def test_zipfile(self, compiled=False):
6646+
script_name = self.make_script(self.dirname, '__main__', compiled=compiled)
6647+
zip_name = self.make_zip_script(script_name)
6648+
self.check_usage(f'{py} {zip_name}', zip_name)
6649+
6650+
def test_zipfile_compiled(self):
6651+
self.test_zipfile(compiled=True)
6652+
6653+
def test_directory_in_zipfile(self, compiled=False):
6654+
script_name = self.make_script(self.dirname, '__main__', compiled=compiled)
6655+
name_in_zip = 'package/subpackage/__main__' + ('.py', '.pyc')[compiled]
6656+
zip_name = self.make_zip_script(script_name, name_in_zip)
6657+
dirname = os.path.join(zip_name, 'package', 'subpackage')
6658+
self.check_usage(f'{py} {dirname}', dirname)
6659+
6660+
def test_directory_in_zipfile_compiled(self):
6661+
self.test_directory_in_zipfile(compiled=True)
6662+
6663+
65646664
def tearDownModule():
65656665
# Remove global references to avoid looking like we have refleaks.
65666666
RFile.seen = {}
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
Improved :ref:`prog` default value for :class:`argparse.ArgumentParser`. It
2+
can now include the name of the Python executable along with the module or
3+
package name, or the path to a directory, ZIP file, or directory within a
4+
ZIP file if the code was run that way.

0 commit comments

Comments
 (0)