我正在尝试通过discord获取用户输入,并使用我自己制作的导入文件将它们转换为命令。这些命令遵循“XX![object] [function]命令。如何将输入的string转换为对象?或者在某种程度上我可以使用与getattr('x','y')类似的东西?

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

我希望这将作为profile.view()执行,但它给我错误AttributeError:'str'对象没有属性'view'。

分析解答

也许你想查看exec()函数:

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

exec(mystring)

>>>> Hello World