Hi Pythonistas!
Today we will learn about a package called fire. This helps us to create CLI application with less effort. Let us dive into the code.
Installation
pip install fire
Function based app
import fire
def hello(name="Pythonista"):
return f"Hello {name}"
if __name__ == '__main__':
fire.Fire(hello)
Run without argument
python fire_intro.py
Output
Hello Pythonista
Run with argument
python fire_intro.py --name Python
Output
Hello Python
Class based App
import fire
class CLIApp:
def add(self, first_number, second_number):
print("first number", first_number)
print("second number", second_number)
result = first_number + second_number
print(f"The result is: {result}")
if __name__ == '__main__':
fire.Fire(CLIApp)
Run without name (with position)
python fire_intro.py add 10 20
Output
first number 10
second number 20
The result is: 30
Run with name
python fire_intro.py add --second_number 10 --first_number 20
Output
first number 20
second number 10
The result is: 30
Some experiments
python fire_intro.py add 10 --second_number 30
Output
first number 10
second number 30
The result is: 40
python fire_intro.py add 10 --first_number 30
Output
first number 30
second number 10
The result is: 40
python fire_intro.py add --first_number 30
Output
ERROR: The function received no value for the required argument: second_number
Usage: fire_intro.py add FIRST_NUMBER SECOND_NUMBER
For detailed information on this command, run:
fire_intro.py add --help
python fire_intro.py add --help
Output
NAME
fire_intro.py add
SYNOPSIS
fire_intro.py add FIRST_NUMBER SECOND_NUMBER
POSITIONAL ARGUMENTS
FIRST_NUMBER
SECOND_NUMBER
NOTES
You can also use flags syntax for POSITIONAL ARGUMENTS
Hope you have learned something from this post. Please share your valuable suggestions and topic suggestions with afsal@parseltongue.co.in