Python Fire, which can generate command-line interfaces from any Python code,Simply call the Fire function in any Python program to automatically convert that program to a CLI.
Acquisition method:
-
Get from pypi `pip install fire`
-
Get from conda`conda install fire -c conda-forge`
-
Install from source, clone code base & `python setup.py install`
What are the advantages of Python Fire:
-
There is no need to define parameters, set help messages or write a main function that defines how the code runs. Simply call the `Fire` function from the main module.
-
Convert any Python object (class, object, dictionary, function, or even an entire module) into a command-line interface, and output annotation labels and documentation.
-
The command line interface is kept up to date in real time as the code changes.
Example 1
1# calling Fire a function
2import fire
3def hello(name="World"):
4 return "Hello %s!" % name
5
6if __name__ == __main__ :
7 fire.Fire(hello)
8
9
10# from the command line,then run:
11python hello.py # Hello World!
12python hello.py --name=David # Hello David!
13python hello.py --help # Shows usage information.
Example 2
1# calling Fire on a class
2import fire
3
4class Calculator(object):
5 """A simple calculator class."""
6
7 def double(self, number):
8 return 2 * number
9
10if __name__ == __main__ :
11 fire.Fire(Calculator)
12
13# from the command line, then run:
14
15python calculator.py double 10 # 20
16python calculator.py double --number=15 # 30
Example 3
1#!/usr/bin/env python
2import fire
3class Example(object):
4 def hello(self, name= world ):
5 """Says hello to the specified name."""
6 return Hello {name}! .format(name=name)
7
8def main():
9 fire.Fire(Example)
10
11if __name__ == __main__ :
12 main()
13
14##########################
15 When the Fire function is run, our command is executed.
16By simply calling Fire, we can now use the sample class as a command line tool.
17
18
19$ ./example.py hello
20Hello world!
21
22$ ./example.py hello David
23Hello David!
24
25$ ./example.py hello --name=Google
26Hello Google!
Each Fire CLI comes with an interactive mode.
-
Use the "-interactive" flag and command line and other defined variables to log into IPython REPL when running the CLI.
-
Be sure to check out the Python Fire documentation to learn more about the useful features of Fire.