从用户inpu运行命令

2024-04-19 22:57:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我想创建一个CLI,它将接受用户的输入,并根据用户输入的内容运行命令

def apple():
    print("Apple")

def orange():
    print("Orange")

def grape():
    print("Grape")


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

userinput()  

我要做的是,当用户输入“Orange”时,它会打印出Orange。苹果和葡萄也一样。我真正的项目将包含更多的功能,用户可以输入,但这是我目前坚持的部分


Tags: 用户命令内容applewhichinputclidef
1条回答
网友
1楼 · 发布于 2024-04-19 22:57:32

如果我理解正确的话,下面是我将如何实现这样的功能:

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

然后可以用Commands.run(input())运行它

相关问题 更多 >