Skip to content
Myr

Merge pull request #1609 from MLH-Fellowship/program-name-detection

Before adoption: this commit came in with the history the project adopted, so no landing records it.

detect program name with python -m

authored by David Lord · committed by GitHub · parents 82ca854, faaec82 · Browse files · 4 files+83 added−3 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

4 files+83 added−3 removed

  • tests:+30 added−0 removed
  • other:+53 added−3 removed

4 files+83 added−3 removed

modified:src/click/core.py+2 added-3 removed
23 unmodified lines
24from .termui import style25from .types import BOOL26from .types import convert_type27from .types import IntRange28from .utils import _detect_program_name29from .utils import echo30from .utils import make_default_short_help31from .utils import make_str32from .utils import PacifyFlushWrapper
762 unmodified lines
795 else:796 args = list(args)797798 if prog_name is None:798 prog_name = make_str(799 os.path.basename(sys.argv[0] if sys.argv else __file__)800 )799 prog_name = _detect_program_name()800801 # Hook for the Bash completion. This only activates if the Bash802 # completion is actually enabled, otherwise this is quite a fast803 # noop.
1284 unmodified lines
modified:src/click/utils.py+49 added
436 unmodified lines
437 raise438439 def __getattr__(self, attr):440 return getattr(self.wrapped, attr)441442443def _detect_program_name(path=None, _main=sys.modules["__main__"]):444 """Determine the command used to run the program, for use in help445 text. If a file or entry point was executed, the file name is446 returned. If ``python -m`` was used to execute a module or package,447 ``python -m name`` is returned.448449 This doesn't try to be too precise, the goal is to give a concise450 name for help text. Files are only shown as their name without the451 path. ``python`` is only shown for modules, and the full path to452 ``sys.executable`` is not shown.453454 :param path: The Python file being executed. Python puts this in455 ``sys.argv[0]``, which is used by default.456 :param _main: The ``__main__`` module. This should only be passed457 during internal testing.458459 .. versionadded:: 8.0460 Based on command args detection in the Werkzeug reloader.461462 :meta private:463 """464 if not path:465 path = sys.argv[0]466467 # The value of __package__ indicates how Python was called. It may468 # not exist if a setuptools script is installed as an egg. It may be469 # set incorrectly for entry points created with pip on Windows.470 if getattr(_main, "__package__", None) is None or (471 os.name == "nt"472 and _main.__package__ == ""473 and not os.path.exists(path)474 and os.path.exists(f"{path}.exe")475 ):476 # Executed a file, like "python app.py".477 return os.path.basename(path)478479 # Executed a module, like "python -m example".480 # Rewritten by Python from "-m script" to "/path/to/script.py".481 # Need to look at main module to determine how it was executed.482 py_module = _main.__package__483 name = os.path.splitext(os.path.basename(path))[0]484485 # A submodule like "example.cli".486 if name != "__main__":487 py_module = f"{py_module}.{name}"488489 return f"python -m {py_module.lstrip('.')}"
modified:tests/test_utils.py+30 added
1import os2import pathlib3import stat4import sys5from io import StringIO6
375 unmodified lines
382 with p.open() as f:383 with click.utils.LazyFile(f.name) as lf:384 for e_line, a_line in zip(expected, lf):385 assert e_line == a_line.strip()386387388class MockMain:389 __slots__ = "__package__"390391 def __init__(self, package_name):392 self.__package__ = package_name393394395@pytest.mark.parametrize(396 ("path", "main", "expected"),397 [398 ("example.py", None, "example.py"),399 (str(pathlib.Path("/foo/bar/example.py")), None, "example.py"),400 ("example", None, "example"),401 (402 str(pathlib.Path("example/__main__.py")),403 MockMain(".example"),404 "python -m example",405 ),406 (407 str(pathlib.Path("example/cli.py")),408 MockMain(".example"),409 "python -m example.cli",410 ),411 ],412)413def test_detect_program_name(path, main, expected):414 assert click.utils._detect_program_name(path, _main=main) == expected
modified:CHANGES.rst+2 added
31 unmodified lines
32- A ``Group`` with ``invoke_without_command=True`` will always invoke33 its result callback. :issue:`1178`34- ``nargs == -1`` and ``nargs > 1`` is parsed and validated for35 values from environment variables and defaults. :issue:`729`36- Detect the program name when executing a module or package with37 ``python -m name``. :issue:`1603`383940Version 7.1.241-------------
635 unmodified lines