Skip to content

Commit 54baaf1

Browse files
Hasan Özdemircursoragent
andcommitted
Use package name when Fire runs from __main__.py
When a package is executed via python -m, show the package name in help output instead of __main__.py. Fixes #76. Co-authored-by: Cursor <cursoragent@cursor.com>
1 parent 716bbc2 commit 54baaf1

2 files changed

Lines changed: 23 additions & 1 deletion

File tree

fire/core.py

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -103,7 +103,7 @@ def Fire(component=None, command=None, name=None, serialize=None):
103103
code 2. When used with the help or trace flags, Fire will raise a
104104
FireExit with code 0 if successful.
105105
"""
106-
name = name or os.path.basename(sys.argv[0])
106+
name = name or _InferCommandName()
107107

108108
# Get args as a list.
109109
if isinstance(command, str):
@@ -275,6 +275,18 @@ def _PrintResult(component_trace, verbose=False, serialize=None):
275275
Display(output, out=sys.stdout)
276276

277277

278+
def _InferCommandName():
279+
"""Return a sensible CLI name when Fire is invoked via python -m package."""
280+
argv0 = sys.argv[0]
281+
base = os.path.basename(argv0)
282+
if base == '__main__.py':
283+
package = sys.modules['__main__'].__package__ # pylint: disable=no-member
284+
if package:
285+
return package
286+
return os.path.basename(os.path.dirname(os.path.abspath(argv0)))
287+
return base
288+
289+
278290
def _DisplayError(component_trace):
279291
"""Prints the Fire trace and the error to stdout."""
280292
result = component_trace.GetResult()

fire/fire_test.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@
2121
import fire
2222
from fire import test_components as tc
2323
from fire import testutils
24+
from fire.core import _InferCommandName
2425

2526

2627
class FireTest(testutils.BaseTestCase):
@@ -57,6 +58,15 @@ def testFireDefaultName(self):
5758
stderr=None):
5859
fire.Fire(tc.Empty)
5960

61+
def testInferCommandNameForMainModule(self):
62+
with mock.patch.object(sys, 'argv', ['sample/__main__.py']):
63+
with mock.patch.object(sys.modules['__main__'], '__package__', 'sample'):
64+
self.assertEqual(_InferCommandName(), 'sample')
65+
66+
def testInferCommandNameForScript(self):
67+
with mock.patch.object(sys, 'argv', ['sample/cli.py']):
68+
self.assertEqual(_InferCommandName(), 'cli.py')
69+
6070
def testFireNoArgs(self):
6171
self.assertEqual(fire.Fire(tc.MixedDefaults, command=['ten']), 10)
6272

0 commit comments

Comments
 (0)