Skip to content

Commit ca4518b

Browse files
pythonGH-155009: Preserve argparse prog for programmatic module-as-main execution (python#155199)
1 parent 83b3354 commit ca4518b

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
@@ -1964,6 +1964,9 @@ def _prog_name(prog=None):
19641964
if modspec is None:
19651965
# simple script
19661966
return _os.path.basename(arg0)
1967+
if modspec.name != '__main__' and arg0 != modspec.origin:
1968+
# named module executed as main without altering sys.argv[0]
1969+
return _os.path.basename(arg0)
19671970
py = _os.path.basename(_sys.executable)
19681971
if modspec.name != '__main__':
19691972
# imported module or package

Lib/test/test_argparse.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7346,6 +7346,19 @@ def test_module(self, compiled=False):
73467346
def test_module_compiled(self):
73477347
self.test_module(compiled=True)
73487348

7349+
def test_module_as_main_without_altering_argv(self):
7350+
basename = 'module' + os_helper.FS_NONASCII
7351+
modulename = f'{self.dirname}.{basename}'
7352+
self.make_script(self.dirname, basename)
7353+
runner_source = textwrap.dedent(f'''\
7354+
import runpy
7355+
runpy._run_module_as_main({modulename!r}, alter_argv=False)
7356+
''')
7357+
runner = script_helper.make_script(
7358+
self.dirname, 'runner', runner_source)
7359+
self.check_usage(os.path.basename(runner), runner,
7360+
PYTHONPATH=os.curdir)
7361+
73497362
def test_package(self, compiled=False):
73507363
basename = 'subpackage' + os_helper.FS_NONASCII
73517364
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)