0

I am wanting to create a CLI that will accept input from the user and run commands based on what they input.

def apple():
    print("Apple")

def orange():
    print("Orange")

def grape():
    print("Grape")


userinput = input("Which function do you want to run? ")

userinput()  

What I am trying to get to work is, when the user enters "Orange" it will print Orange. Same for apple and grape. My real project will incorporate a lot more functions the user can input but this is the part I am stuck on at the moment.

Mad Physicist
  • 107,652
  • 25
  • 181
  • 264
Doritos
  • 403
  • 3
  • 16
  • I am unclear as to what exactly you are asking. – Mad Physicist Feb 12 '19 at 16:26
  • `globals()[userinput]()`? – Azat Ibrakov Feb 12 '19 at 16:28
  • Combine [this](https://stackoverflow.com/q/3061/2988730) with [this](https://stackoverflow.com/q/990422/2988730) (mostly the second one), and you're good to go. – Mad Physicist Feb 12 '19 at 16:28
  • @AzatIbrakov. I'd go with `globals` since you're eventually going to want to stick that into a function, but same difference. – Mad Physicist Feb 12 '19 at 16:28
  • @MadPhysicist: sure, I've used `vars` because it was shorter and in given context will behave like `globals` (but `globals` obviously is a correct choice) – Azat Ibrakov Feb 12 '19 at 16:30
  • @AzatIbrakov. While we both know what to do, I still have no idea what OP is actually asking. There is a "want" and some requirements, and while those are spelled out clearly enough, there is no implied action on our part that isn't out of scope. – Mad Physicist Feb 12 '19 at 16:34

1 Answers1

1

If I understood you correctly, here's how I would implement something like that:

class Commands:
    @staticmethod
    def _apple():
        print("Apple")

    @staticmethod
    def _orange():
        print("Orange")

    @staticmethod
    def _grape():
        print("Grape")

    def run(self, cmd_name):
        getattr(Commands, '_' + cmd_name.lower())()

You can then run it with Commands.run(input())

Tom Gringauz
  • 801
  • 8
  • 16
  • Yes this is exactly what I was wanting. i was looking into the getattr command but I wasn't fully understanding it. This helps to understand. – Doritos Feb 12 '19 at 16:46