Skip to content

[Python] How to use "Fire" package to use function via command line

Last Updated on 2021-04-05 by Clay

Recently, I was learning about various deep learning models implemented by many masters in Python, and I see a unfamiliar package: Fire.

I didn't know what kind of package Fire is at first, I just thought the name was weird. After a check, it turns out that this turned out to be Google's open source package on Github in 2017.

Since it is open sourced by Google, this package is reasonable. The biggest advantage of the Fire package is that you can "use terminal command line to enter parameters to program".

What does it mean?

I wonder if you are familiar with the argparse package? OR you are familiar with sys.argv? The above two are module that allow user to enter parameters when executing Python files on command line.

If you are not familiar with it and want to understand the operation method, you may consider referring to: [Python] How to use argparse package to give the arguments in terminal

Basically, the parameters given from the terminal command line looks like this:

Python3  "file.py" --arg arg

The argparse module need to set the variables we want to use; But if you use Fire package, you can directly use Functions or Classes name to be arguments.


How to use Fire package

I can not explain it clearly in words, so I will demo it.

If you use this package in the first time, you can use the following command to install it:

pip3 install fire


We write down two functions.

# -*- coding: utf-8 -*-
import fire


def printHelloWorld():
    return 'Hello World!'


def name(name):
    return 'your name is {}.'.format(name)


if __name__ == '__main__':
    fire.Fire()


Output:

NAME
    fire_test.py

SYNOPSIS
    fire_test.py GROUP | COMMAND

GROUPS
    GROUP is one of the following:
     fire
       The Python Fire module.

COMMANDS
    COMMAND is one of the following:
     printHelloWorld
     name

In the bottom of this program, we use fire.Fire() function to activate this package.

fire_test.py is my file name, function we defined will under COMMANDS block, they are the arguments we can input in terminal command line.

If we want to use this program, we need to do the following step in terminal:

python3 fire_test.py printHelloWorld

Output:

Hello World!


If you have some value to input program as arguments, you need to add it after argument name.

python3 fire_test.py name "Clay"

Output:

your name is Clay.

Leave a Reply