Skip to content

Commit f20b504

Browse files
[3.15] GH-155009: Preserve argparse prog for programmatic module-as-main execution (GH-155199) (#155200)
GH-155009: Preserve argparse prog for programmatic module-as-main execution (GH-155199) (cherry picked from commit ca4518b) Co-authored-by: Savannah Ostrowski <savannah@python.org>
1 parent b1dd489 commit f20b504

3 files changed

Lines changed: 19 additions & 0 deletions

File tree

Lib/argparse.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1968,6 +1968,9 @@ def _prog_name(prog=None):
19681968
if modspec is None:
19691969
# simple script
19701970
return _os.path.basename(arg0)
1971+
if modspec.name != '__main__' and arg0 != modspec.origin:
1972+
# named module executed as main without altering sys.argv[0]
1973+
return _os.path.basename(arg0)
19711974
py = _os.path.basename(_sys.executable)
19721975
if modspec.name != '__main__':
19731976
# imported module or package

Lib/test/test_argparse.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7341,6 +7341,19 @@ def test_module(self, compiled=False):
73417341
def test_module_compiled(self):
73427342
self.test_module(compiled=True)
73437343

7344+
def test_module_as_main_without_altering_argv(self):
7345+
basename = 'module' + os_helper.FS_NONASCII
7346+
modulename = f'{self.dirname}.{basename}'
7347+
self.make_script(self.dirname, basename)
7348+
runner_source = textwrap.dedent(f'''\
7349+
import runpy
7350+
runpy._run_module_as_main({modulename!r}, alter_argv=False)
7351+
''')
7352+
runner = script_helper.make_script(
7353+
self.dirname, 'runner', runner_source)
7354+
self.check_usage(os.path.basename(runner), runner,
7355+
PYTHONPATH=os.curdir)
7356+
73447357
def test_package(self, compiled=False):
73457358
basename = 'subpackage' + os_helper.FS_NONASCII
73467359
packagename = f'{self.dirname}.{basename}'
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
Fix :class:`argparse.ArgumentParser` to preserve the program name from
2+
``sys.argv[0]`` when a named module is executed as the main program without
3+
replacing ``sys.argv[0]``.

0 commit comments

Comments
 (0)