]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
GH-155009: Preserve argparse prog for programmatic module-as-main execution (#155199)
authorSavannah Ostrowski <savannah@python.org>
Wed, 5 Aug 2026 04:43:08 +0000 (21:43 -0700)
committerGitHub <noreply@github.com>
Wed, 5 Aug 2026 04:43:08 +0000 (04:43 +0000)
Lib/argparse.py
Lib/test/test_argparse.py
Misc/NEWS.d/next/Library/2026-08-05-02-36-18.gh-issue-155009.YiJAiP.rst [new file with mode: 0644]

index 0840c4c45cffaa2d3ae83cfb22ac7b74621384dd..25994d7a389efac683a56766c81568a60f194aec 100644 (file)
@@ -1964,6 +1964,9 @@ def _prog_name(prog=None):
     if modspec is None:
         # simple script
         return _os.path.basename(arg0)
+    if modspec.name != '__main__' and arg0 != modspec.origin:
+        # named module executed as main without altering sys.argv[0]
+        return _os.path.basename(arg0)
     py = _os.path.basename(_sys.executable)
     if modspec.name != '__main__':
         # imported module or package
index 287fcb7a084a49942eb188bba27beef612c79b04..ae02cd11804e50756f47b950412a081adeef2826 100644 (file)
@@ -7346,6 +7346,19 @@ class TestProgName(TestCase):
     def test_module_compiled(self):
         self.test_module(compiled=True)
 
+    def test_module_as_main_without_altering_argv(self):
+        basename = 'module' + os_helper.FS_NONASCII
+        modulename = f'{self.dirname}.{basename}'
+        self.make_script(self.dirname, basename)
+        runner_source = textwrap.dedent(f'''\
+            import runpy
+            runpy._run_module_as_main({modulename!r}, alter_argv=False)
+        ''')
+        runner = script_helper.make_script(
+            self.dirname, 'runner', runner_source)
+        self.check_usage(os.path.basename(runner), runner,
+                         PYTHONPATH=os.curdir)
+
     def test_package(self, compiled=False):
         basename = 'subpackage' + os_helper.FS_NONASCII
         packagename = f'{self.dirname}.{basename}'
diff --git a/Misc/NEWS.d/next/Library/2026-08-05-02-36-18.gh-issue-155009.YiJAiP.rst b/Misc/NEWS.d/next/Library/2026-08-05-02-36-18.gh-issue-155009.YiJAiP.rst
new file mode 100644 (file)
index 0000000..219c6a9
--- /dev/null
@@ -0,0 +1,3 @@
+Fix :class:`argparse.ArgumentParser` to preserve the program name from
+``sys.argv[0]`` when a named module is executed as the main program without
+replacing ``sys.argv[0]``.