-1

I'm trying to take user inputs through discord and turn them into commands using imported files of my own making. The commands follow a "XX! [object] [function] command. How do I turn an inputted string into a object? Or is there someway that I can use something similar to getattr('x', 'y')?

def function():
    x = "XX! profile view"
    getattr(x.lower().split(" ")[1], x.lower().split(" ")[2])()
    return

I was hoping that would execute as profile.view(), but its giving me the error AttributeError: 'str' object has no attribute 'view'.

2 Answers2

1

Better to not use function string names. Correct way is to create dict which match string name with function.

def XX(*args):
    print(list(reversed(*args)))


def YY(*args):
    print(list(map(str.upper, *args)))


router = {
    "XX": XX,
    "YY": YY
}


def interpret(string):
    if any(string.startswith(key) for key in router):
        func_name = string[0: string.index("!")]
        args = string[string.index("!") + 2:].split(" ")
        router[func_name](args)


x = "YY! profile view"

interpret(x)
Olvin Roght
  • 7,677
  • 2
  • 16
  • 35
0

Perhaps you want to look into the exec() function:

mystring = r'print("Hello World")'

exec(mystring)

>>>> Hello World
Jkind9
  • 742
  • 7
  • 24