DEV Community

petercour
petercour

Posted on

2

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:

Sentry image

Make it make sense

Make sense of fixing your code with straight-forward application monitoring.

Start debugging →

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Engage with a wealth of insights in this thoughtful article, valued within the supportive DEV Community. Coders of every background are welcome to join in and add to our collective wisdom.

A sincere "thank you" often brightens someone’s day. Share your gratitude in the comments below!

On DEV, the act of sharing knowledge eases our journey and fortifies our community ties. Found value in this? A quick thank you to the author can make a significant impact.

Okay