Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions Lib/argparse.py
Original file line number Diff line number Diff line change
Expand Up @@ -1829,6 +1829,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
Expand Down
13 changes: 13 additions & 0 deletions Lib/test/test_argparse.py
Original file line number Diff line number Diff line change
Expand Up @@ -7128,6 +7128,19 @@ def test_module(self, compiled=False):
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}'
Expand Down
Original file line number Diff line number Diff line change
@@ -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]``.
Loading