使用 exec 调用函数

Calling a function using exec

尝试使用 exec 将函数作为字符串调用,但它不起作用。我在下面附上了一个简单的示例代码。

我收到一条错误消息,指出 square_it() 缺少 1 个必需的位置参数:'num.' 我知道它丢失了,但我不知道如何在该全局语法中包含该参数。

下面是一个例子:

def square_it(num):

    result = num * num
    return result

def test():

    #code_globals = {}
    globals()['square_it']()
    code_locals = {'testing':0}
    comd_str = "testing = square_it(2)"
    exec(comd_str, globals(), code_locals)
    print(code_locals['testing'])


test()

exec 调用中没有发生错误;当您调用全局变量时,它发生在第一行。其余所有代码均无关紧要。

调用那里的函数完全与以任何其他方式调用函数相同;你有调用括号,你只需要把你的论点放在那里:

globals()['square_it'](2)