detect program name when run with python -m
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by kbanc · committed by David Lord · parent 82ca854 · 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.
Trailers
- Co-authored-by: Gabriel de Melo Cruz <gabrieldemelocruz@gmail.com>
Diff stats
4 files+83 added−3 removed
- tests:+30 added−0 removed
- other:+53 added−3 removed
Provenance
- Commit
faaec82- Tree
d0756c0- Author
kbanc <katherine.bancroft@gmail.com>- Committer
David Lord <davidism@gmail.com>- Parent
82ca854
4 files changed+83 added−3 removed
modified:src/click/core.py+2 added-3 removed
23 unmodified lines24 from .termui import style25 from .types import BOOL26 from .types import convert_type27 from .types import IntRange28+from .utils import _detect_program_name29 from .utils import echo30 from .utils import make_default_short_help31 from .utils import make_str32 from .utils import PacifyFlushWrapper762 unmodified lines795 else:796 args = list(args)797 798 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()800 801 # Hook for the Bash completion. This only activates if the Bash802 # completion is actually enabled, otherwise this is quite a fast803 # noop.1284 unmodified linesmodified:src/click/utils.py+49 added
436 unmodified lines437 raise438 439 def __getattr__(self, attr):440 return getattr(self.wrapped, attr)441+442+443+def _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.448+449+ 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.453+454+ :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.458+459+ .. versionadded:: 8.0460+ Based on command args detection in the Werkzeug reloader.461+462+ :meta private:463+ """464+ if not path:465+ path = sys.argv[0]466+467+ # 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)478+479+ # 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]484+485+ # A submodule like "example.cli".486+ if name != "__main__":487+ py_module = f"{py_module}.{name}"488+489+ return f"python -m {py_module.lstrip('.')}"modified:tests/test_utils.py+30 added
1 import os2+import pathlib3 import stat4 import sys5 from io import StringIO6 375 unmodified lines382 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()386+387+388+class MockMain:389+ __slots__ = "__package__"390+391+ def __init__(self, package_name):392+ self.__package__ = package_name393+394+395+@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+)413+def test_detect_program_name(path, main, expected):414+ assert click.utils._detect_program_name(path, _main=main) == expectedmodified:CHANGES.rst+2 added
31 unmodified lines32 - 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`38 39 40 Version 7.1.241 -------------635 unmodified lines