From ac5a3918855bca3b8c227a3ce59aabebae5c83dc Mon Sep 17 00:00:00 2001 From: KOLANICH Date: Tue, 5 Dec 2017 14:02:16 +0300 Subject: [PATCH] Added main module detection and cli construction, now should show the right name (instead of __main__.py) when called for modules --- plumbum/cli/application.py | 11 +++++++++-- plumbum/lib.py | 9 +++++++++ 2 files changed, 18 insertions(+), 2 deletions(-) diff --git a/plumbum/cli/application.py b/plumbum/cli/application.py index 580be6f8f..d90fafaf9 100644 --- a/plumbum/cli/application.py +++ b/plumbum/cli/application.py @@ -2,10 +2,11 @@ import os import sys import functools +import re from textwrap import TextWrapper from collections import defaultdict -from plumbum.lib import six, getdoc +from plumbum.lib import six, getdoc, get_main_module_frame from .terminal import get_terminal_size from .switches import (SwitchError, UnknownSwitch, MissingArgument, WrongArgumentType, MissingMandatorySwitch, SwitchCombinationError, PositionalArgumentsError, switch, @@ -58,6 +59,8 @@ def __repr__(self): # CLI Application base class #=================================================================================================== +main_module_ending_rx=re.compile("\.__main__$") + class Application(object): """ The base class for CLI applications; your "entry point" class should derive from it, @@ -144,7 +147,11 @@ def __init__(self, executable): # Filter colors if self.PROGNAME is None: - self.PROGNAME = os.path.basename(executable) + spec=get_main_module_frame().f_globals['__spec__'] + if spec: + self.PROGNAME = " ".join(("python -m", main_module_ending_rx.sub("", spec.name))) + else: + self.PROGNAME = os.path.basename(executable) elif isinstance(self.PROGNAME, colors._style): self.PROGNAME = self.PROGNAME | os.path.basename(executable) elif colors.filter(self.PROGNAME) == '': diff --git a/plumbum/lib.py b/plumbum/lib.py index 69ffe15ba..5e67375f8 100644 --- a/plumbum/lib.py +++ b/plumbum/lib.py @@ -141,3 +141,12 @@ def read_fd_decode_safely(fd, size=4096): if i == 3: raise data += os.read(fd.fileno(), 1) + +def get_main_module_frame(): + """ + Gets the frame of the __main__ module (the one which is called with command line) of an app. + """ + fr=sys._getframe(0) + while fr and fr.f_globals['__name__'] != '__main__': + fr=fr.f_back + return fr