Generate CLI for any Python object

petercour

petercour

Posted on July 2, 2019

Generate CLI for any Python object

You can generate command line interfaces (CLI) easily with the fire module. For the Linux or Apple terminal.

This is for a Python object, so you need to know the object oriented programming paradigm.

class Bot():
    def hello(self, name):
        print("Hello " + name)

    def whatsup(self):
        print("All good!")
Enter fullscreen mode Exit fullscreen mode

Then import the fire module and load it in the main function.

import fire

class Bot():
    def hello(self, name):
        print("Hello " + name)

    def whatsup(self):
        print("All good!")

if __name__ == '__main__':
    fire.Fire(Bot)
Enter fullscreen mode Exit fullscreen mode

Then in the command line:

λ  ~  python example.py
Type:        instance
String form: <__main__.Bot instance at 0x7fa7e1062320>

Usage:       example.py 
             example.py hello
             example.py whatsup
Enter fullscreen mode Exit fullscreen mode

Need to write arguments with the command :)

You can do:

λ  ~  python example.py hello bob
Hello bob
Enter fullscreen mode Exit fullscreen mode

To call the other method

λ  ~  python example.py whatsup  
All good!
λ  ~  
Enter fullscreen mode Exit fullscreen mode

Yes, all methods of the class are included.

More on Python:

💖 💪 🙅 🚩
petercour
petercour

Posted on July 2, 2019

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related