python-fire
Python Fire is a library for automatically generating command line interfaces (CLIs) from absolutely any Python object.
Top Related Projects
Python composable command line interface toolkit
Create *beautiful* command-line interfaces with Python
Typer, build great CLIs. Easy to code. Based on Python type hints.
A Commander for modern Go CLI interactions
CONTRIBUTIONS ONLY: A Go (golang) command line and flag parser
Quick Overview
Google's Python Fire is a library that automatically generates command-line interfaces (CLIs) from any Python object. It allows developers to easily create CLIs for their Python code without writing additional interface code, making it simple to turn any Python module, class, object, or function into a CLI.
Pros
- Simplifies the process of creating CLIs for Python projects
- Requires minimal additional code to implement
- Automatically generates help messages and usage information
- Supports a wide range of Python objects and data types
Cons
- May not provide as much fine-grained control over CLI behavior as other libraries
- Can sometimes produce unexpected results with complex object structures
- Limited customization options for generated help messages
- May not be suitable for very large or complex CLI applications
Code Examples
- Basic function example:
import fire
def hello(name="World"):
return f"Hello {name}!"
if __name__ == '__main__':
fire.Fire(hello)
This example creates a simple CLI that accepts an optional name parameter.
- Class method example:
import fire
class Calculator:
def add(self, x, y):
return x + y
def multiply(self, x, y):
return x * y
if __name__ == '__main__':
fire.Fire(Calculator)
This example creates a CLI with two commands: add
and multiply
.
- Nested command example:
import fire
class NestedCommands:
class Git:
def commit(self, message):
return f"Committing with message: {message}"
def push(self, remote="origin", branch="main"):
return f"Pushing to {remote}/{branch}"
if __name__ == '__main__':
fire.Fire(NestedCommands)
This example creates a CLI with nested commands, simulating a git-like interface.
Getting Started
-
Install Python Fire:
pip install fire
-
Import Fire in your Python script:
import fire
-
Use Fire to create a CLI from your Python object:
if __name__ == '__main__': fire.Fire(YourObject)
-
Run your script from the command line, passing arguments as needed:
python your_script.py [command] [arguments]
Competitor Comparisons
Python composable command line interface toolkit
Pros of Click
- More mature and widely adopted in the Python community
- Extensive documentation and comprehensive feature set
- Supports nested command groups for complex CLI structures
Cons of Click
- Steeper learning curve for beginners
- More verbose syntax for simple use cases
- Requires explicit type annotations for arguments
Code Comparison
Click:
import click
@click.command()
@click.option('--count', default=1, help='Number of greetings.')
@click.option('--name', prompt='Your name', help='The person to greet.')
def hello(count, name):
for _ in range(count):
click.echo(f"Hello, {name}!")
Python Fire:
import fire
def hello(name='World', count=1):
for _ in range(count):
print(f"Hello, {name}!")
if __name__ == '__main__':
fire.Fire(hello)
Both Click and Python Fire are popular libraries for creating command-line interfaces in Python. Click offers more features and flexibility, making it suitable for complex applications, while Python Fire provides a simpler, more intuitive approach for quick CLI creation. The choice between them depends on the project's requirements and the developer's preferences.
Create *beautiful* command-line interfaces with Python
Pros of docopt
- Declarative approach using docstrings for defining CLI interfaces
- Supports a wide range of programming languages, not just Python
- Generates help messages automatically from the docstring
Cons of docopt
- Less flexible for complex command structures
- Limited support for argument validation and type conversion
- Development appears to be less active compared to python-fire
Code Comparison
docopt example:
"""Naval Fate.
Usage:
naval_fate ship <name> move <x> <y> [--speed=<kn>]
naval_fate ship shoot <x> <y>
naval_fate mine (set|remove) <x> <y> [--moored|--drifting]
naval_fate -h | --help
naval_fate --version
Options:
-h --help Show this screen.
--version Show version.
--speed=<kn> Speed in knots [default: 10].
--moored Moored (anchored) mine.
--drifting Drifting mine.
"""
python-fire example:
import fire
class Ship:
def move(self, x, y, speed=10):
print(f"Moving ship to ({x}, {y}) at {speed} knots")
def shoot(self, x, y):
print(f"Shooting at ({x}, {y})")
if __name__ == '__main__':
fire.Fire(Ship)
Typer, build great CLIs. Easy to code. Based on Python type hints.
Pros of Typer
- More modern and actively maintained
- Better type hinting and autocompletion support
- Integrates well with FastAPI ecosystem
Cons of Typer
- Steeper learning curve for beginners
- Less flexibility in command structure compared to Fire
Code Comparison
Typer:
import typer
app = typer.Typer()
@app.command()
def hello(name: str):
typer.echo(f"Hello {name}")
if __name__ == "__main__":
app()
Fire:
import fire
def hello(name):
print(f"Hello {name}")
if __name__ == '__main__':
fire.Fire(hello)
Both Python-Fire and Typer are libraries for creating command-line interfaces (CLIs) in Python. Fire offers simplicity and automatic CLI generation, while Typer provides more structure and type safety. Typer is newer and integrates well with FastAPI, but may have a steeper learning curve. Fire is more flexible but lacks some modern features. The choice between them depends on project requirements and developer preferences.
A Commander for modern Go CLI interactions
Pros of Cobra
- Written in Go, offering better performance and compilation to a single binary
- More extensive CLI features, including nested subcommands and auto-generated help
- Larger ecosystem with additional tools and plugins
Cons of Cobra
- Steeper learning curve compared to Fire's simplicity
- Requires more boilerplate code to set up commands and flags
- Limited to Go language, while Fire supports Python
Code Comparison
Cobra:
var rootCmd = &cobra.Command{
Use: "app",
Short: "A brief description of your application",
Run: func(cmd *cobra.Command, args []string) {
// Your code here
},
}
Fire:
import fire
def hello(name="World"):
return f"Hello {name}!"
if __name__ == '__main__':
fire.Fire(hello)
Summary
Cobra is a powerful CLI framework for Go, offering extensive features and better performance. However, it comes with a steeper learning curve and more verbose setup. Fire, on the other hand, provides a simpler approach in Python, allowing for quick CLI creation with minimal code. The choice between the two depends on the project's requirements, language preference, and desired level of CLI complexity.
CONTRIBUTIONS ONLY: A Go (golang) command line and flag parser
Pros of Kingpin
- More structured and explicit command-line interface definition
- Supports advanced features like required flags and command aliases
- Provides built-in help generation and usage documentation
Cons of Kingpin
- Steeper learning curve due to more complex API
- Requires more boilerplate code to set up commands and flags
- Less flexibility for dynamic command generation
Code Comparison
Kingpin:
import kingpin
app = kingpin.Application("chat", "A chat application.")
app.add_flag("--debug", help="Enable debug mode.")
app.add_command("send", "Send a message.")
Python Fire:
import fire
class Chat:
def send(self, message):
print(f"Sending: {message}")
if __name__ == '__main__':
fire.Fire(Chat)
Kingpin requires more explicit setup but offers more control over the CLI structure. Python Fire provides a simpler interface, automatically generating commands from class methods, but with less customization options for command-line behavior.
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
Python Fire
Python Fire is a library for automatically generating command line interfaces (CLIs) from absolutely any Python object.
- Python Fire is a simple way to create a CLI in Python. [1]
- Python Fire is a helpful tool for developing and debugging Python code. [2]
- Python Fire helps with exploring existing code or turning other people's code into a CLI. [3]
- Python Fire makes transitioning between Bash and Python easier. [4]
- Python Fire makes using a Python REPL easier by setting up the REPL with the modules and variables you'll need already imported and created. [5]
Installation
To install Python Fire with pip, run: pip install fire
To install Python Fire with conda, run: conda install fire -c conda-forge
To install Python Fire from source, first clone the repository and then run:
python setup.py install
Basic Usage
You can call Fire
on any Python object:
functions, classes, modules, objects, dictionaries, lists, tuples, etc.
They all work!
Here's an example of calling Fire on a function.
import fire
def hello(name="World"):
return "Hello %s!" % name
if __name__ == '__main__':
fire.Fire(hello)
Then, from the command line, you can run:
python hello.py # Hello World!
python hello.py --name=David # Hello David!
python hello.py --help # Shows usage information.
Here's an example of calling Fire on a class.
import fire
class Calculator(object):
"""A simple calculator class."""
def double(self, number):
return 2 * number
if __name__ == '__main__':
fire.Fire(Calculator)
Then, from the command line, you can run:
python calculator.py double 10 # 20
python calculator.py double --number=15 # 30
To learn how Fire behaves on functions, objects, dicts, lists, etc, and to learn about Fire's other features, see the Using a Fire CLI page.
For additional examples, see The Python Fire Guide.
Why is it called Fire?
When you call Fire
, it fires off (executes) your command.
Where can I learn more?
Please see The Python Fire Guide.
Reference
Setup | Command | Notes |
---|---|---|
install | pip install fire |
Creating a CLI | Command | Notes |
---|---|---|
import | import fire | |
Call | fire.Fire() | Turns the current module into a Fire CLI. |
Call | fire.Fire(component) | Turns component into a Fire CLI. |
Using a CLI | Command | Notes |
---|---|---|
Help | command --help or command -- --help | |
REPL | command -- --interactive | Enters interactive mode. |
Separator | command -- --separator=X | Sets the separator to X . The default separator is - . |
Completion | command -- --completion [shell] | Generates a completion script for the CLI. |
Trace | command -- --trace | Gets a Fire trace for the command. |
Verbose | command -- --verbose |
Note that these flags are separated from the Fire command by an isolated --
.
License
Licensed under the Apache 2.0 License.
Disclaimer
This is not an official Google product.
Top Related Projects
Python composable command line interface toolkit
Create *beautiful* command-line interfaces with Python
Typer, build great CLIs. Easy to code. Based on Python type hints.
A Commander for modern Go CLI interactions
CONTRIBUTIONS ONLY: A Go (golang) command line and flag parser
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot