diff --git a/fire/core.py b/fire/core.py index 3a0712e9..f49422d2 100644 --- a/fire/core.py +++ b/fire/core.py @@ -70,7 +70,7 @@ def main(argv): import six -def Fire(component=None, command=None, name=None): +def Fire(component=None, command=None, name=None, formatter=None): """This function, Fire, is the main entrypoint for Python Fire. Executes a command either from the `command` argument or from sys.argv by @@ -85,6 +85,7 @@ def Fire(component=None, command=None, name=None): supplied, then the command is taken from sys.argv instead. name: Optional. The name of the command as entered at the command line. Used in interactive mode and for generating the completion script. + formatter: Optional. Function to be called for output formatting. (result object passed to formatter) Returns: The result of executing the Fire command. Execution begins with the initial target component. The component is updated by using the command arguments @@ -153,8 +154,13 @@ def Fire(component=None, command=None, name=None): file=sys.stderr) raise FireExit(0, component_trace) else: - _PrintResult(component_trace, verbose=component_trace.verbose) result = component_trace.GetResult() + if formatter and args and '--' not in args: + formatter(result) + elif formatter and not args: + print(helputils.HelpString(result, component_trace, component_trace.verbose)) + else: + _PrintResult(component_trace, verbose=component_trace.verbose) return result diff --git a/fire/helputils.py b/fire/helputils.py index 5c23de3a..143b110c 100644 --- a/fire/helputils.py +++ b/fire/helputils.py @@ -23,6 +23,7 @@ from __future__ import print_function import inspect +import os from fire import completion from fire import inspectutils @@ -105,7 +106,15 @@ def HelpString(component, trace=None, verbose=False): 'usage', ] + display_fields = [ + 'docstring', + 'init_docstring', + 'class_docstring', + 'call_docstring', + 'length', + 'usage', + ] max_size = max( len(_NormalizeField(field)) + 1 for field in fields @@ -113,12 +122,20 @@ def HelpString(component, trace=None, verbose=False): format_string = '{{field:{max_size}s}} {{value}}'.format(max_size=max_size) lines = [] + source_filepath = None for field in fields: value = _DisplayValue(info, field, padding=max_size + 1) - if value: + if field == 'file': + source_filepath = value # assumes that 'file' comes before usage (See 'fields' above) + if value and field in display_fields: if lines and field == 'usage': lines.append('') # Ensure a blank line before usage. + # use package_name if file called is __main__.py + if source_filepath and source_filepath.endswith('__main__.py'): + package_path, _ = os.path.split(source_filepath) + _, package_name = os.path.split(package_path) + value = value.replace('__main__.py', package_name) lines.append(format_string.format( field=_NormalizeField(field) + ':', value=value,