首页 > 解决方案 > 输入一个函数,得到“str”对象不可调用

问题描述

我正在尝试用 Python 制作一个命令提示符样式的程序。我想要一个可能运行的函数列表,然后检查列表;如果其中任何一个匹配,则获取匹配的输入并调用具有相同名称的函数。我目前收到一个"str" object is not callable错误。

import os
import time

able_commands = ["clear", "test"]


def test():
    print("worked")


def run_command(command):
    command()
    input_command()


def clear():
    print("clearing...")
    time.sleep(2)
    os.system('cls')


def input_command():
    command = input(os.path.abspath(os.sep) + " ")
    check_if = command.lower()
    if check_if in able_commands:
        run_command(check_if)
    elif check_if == "":
        input_command()
    else:
        print("ERROR \nPlease specify a valid command")
        input_command()


input_command()

我是 Python 的初学者。

标签: python

解决方案


在 Python 中,函数是一流的对象。所以,你可以这样做:

def foo():
    print('foo')

def bar():
    print('bar')

# Create a dict of function name to the function object. 
# This dict must be declared after your functions otherwise
# you will get a NameError exception.
funcs = {
   'run_foo': foo
   'run_bar': bar
}

# Select the function from the dict
f = funcs['run_foo']

# Run the selected function
f()

推荐阅读