@@ -109,7 +109,8 @@ def Fire(component=None, command=None, name=None, serialize=None):
109109 code 2. When used with the help or trace flags, Fire will raise a
110110 FireExit with code 0 if successful.
111111 """
112- name = name or os .path .basename (sys .argv [0 ])
112+
113+ name = _GetProgName (name )
113114
114115 # Get args as a list.
115116 if isinstance (command , six .string_types ):
@@ -281,6 +282,45 @@ def _PrintResult(component_trace, verbose=False, serialize=None):
281282 Display (output , out = sys .stdout )
282283
283284
285+ def _GetProgName (name , main = None ):
286+ """Determines the program name.
287+
288+ This function returns the program name that should be
289+ displayed.
290+
291+ If ``python -m`` was used to execute a module, ``python -m name`` will be
292+ returned, instead of ``__main__.py``.
293+
294+ Args:
295+ name: Optional. The name of the command as entered at the command line.
296+ main: Optional. This should only be passed during testing.
297+ Returns:
298+ The program name determined by this function.
299+ """
300+ if name :
301+ return name
302+
303+ name_from_arg = os .path .basename (sys .argv [0 ])
304+
305+ if main :
306+ py_module = main
307+ else :
308+ py_module = sys .modules ['__main__' ].__package__ # pylint: disable=no-member
309+
310+ if py_module is not None :
311+ if name_from_arg == '__main__.py' :
312+ return '{executable} -m {module}' .format (
313+ executable = sys .executable , module = py_module )
314+ else :
315+ # For example: python -m sample.cli
316+ name = os .path .splitext (name_from_arg )[0 ]
317+ py_module = '{module}.{name}' .format (module = py_module , name = name )
318+ return '{executable} -m {module}' .format (
319+ executable = sys .executable , module = py_module .lstrip ('.' ))
320+ else :
321+ return name_from_arg
322+
323+
284324def _DisplayError (component_trace ):
285325 """Prints the Fire trace and the error to stdout."""
286326 result = component_trace .GetResult ()
0 commit comments