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.

6
  • I am unclear as to what exactly you are asking. Commented Feb 12, 2019 at 16:26
  • globals()[userinput]()? Commented Feb 12, 2019 at 16:28
  • Combine this with this (mostly the second one), and you're good to go. Commented Feb 12, 2019 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. Commented Feb 12, 2019 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) Commented Feb 12, 2019 at 16:30

1 Answer 1

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())

Sign up to request clarification or add additional context in comments.

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.