How to Create a CLI with Python Fire on Ubuntu 22.04
Introduction to Create a CLI
Python Fire is a Python library that lets you automatically create CLIs (command line interfaces) from Python objects. CLIs are programs that take text input from the command line and can be helpful for developing and debugging workflows. This can be especially useful for those comfortable working in Bash and the command line.
While the traditional method of using argparse
from the standard Python library can achieve similar results, Python Fire improves prototyping and maintenance. If you need complete control, check out the tutorial on how to use argparse
to write command line programs in Python.
In this tutorial, you will install Python Fire and use it to create custom CLIs. These CLIs can be created without modifying Python source code or by integrating Python Fire directly into your functions and classes for more granular control.
Prerequisites to Create a CLI
- An Ubuntu 22.04 server set up with a non-root user with sudo privileges and a firewall enabled.
- The latest version of Python 3 installed on your machine with a virtual environment created.
- Familiarity with Python programming. A good primer is this series on how to code in Python 3.
Step 1 — Installing Python Fire
Python Fire is hosted on PyPI and is installable via pip. Ensure your virtual environment is activated:
cd environments
source my_env/bin/activate
pip install fire
This installation ensures no interference with global pip installations, which might conflict with package managers like apt.
Step 2 — Create a CLI from a Program without Code Additions
Create a new Python file:
nano example.py
Add the following code:
def my_name(name):
return "My name is {name}".format(name=name)
Save and exit the file. To execute this as a CLI, run:
python -m fire example my_name --name=sammy
Output:
My name is sammy
Step 3 — Create a CLI with Python Fire Imported
Edit the file to include Python Fire:
import fire
def my_name(name):
return "My name is {name}".format(name=name)
if __name__ == '__main__':
fire.Fire()
Now you can run the CLI with:
python example.py my_name sammy
Output:
My name is sammy
Step 4 — Create a CLI from a Function
Update the code to specify the function:
import fire
def my_name(name):
return "My name is {name}".format(name=name)
if __name__ == '__main__':
fire.Fire(my_name)
Run:
python example.py sammy
Output:
My name is sammy
Step 5 — Create a CLI from a Class
Refactor your code into a class:
import fire
class Namer(object):
def my_name(self, name):
return "My name is {name}".format(name=name)
if __name__ == '__main__':
fire.Fire(Namer)
Use the CLI:
python example.py my_name sammy
Output:
My name is sammy
Conclusion
In this tutorial, you installed Python Fire and explored various ways to create CLIs using Python programs, functions, and classes. For a deeper dive, refer to the official documentation or explore how to use argparse
for creating command line programs in Python.