Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
358 views
in Technique[技术] by (71.8m points)

python - input a function, get "str" object is not callable

I'm trying to make a command prompt style program in Python. I want to have a list of possible functions to run, and then check the list; if any of them match, take the input that matched and call a function with the same name. I currently get a "str" object is not callable error.

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 
Please specify a valid command")
        input_command()


input_command()

I'm a beginner with Python.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

In Python, functions are first-class objects. So, you could do something like this:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...