如何将 eval 用于 运行 其他 python 带有参数的脚本?

How to use eval to run other python script with argument?

我有一个 python 文件 a.py 包含代码:

var=50*10
data= # eval here to call add function of b.py with argument var
print(data)

和 b.py 包含代码:

def add(h):
    res=h+10
    return res

现在我想要的是使用 eval 从 a.py python 脚本中使用参数调用 b.py 的 运行 函数并获得结果。 但我无法理解 eval 在这里是如何工作的。我看过 python 官方文档,它们超出了我的理解范围。 或者如果不是 eval 那么其他选项是什么(除了使用其他文件作为模块)

你只需要这样写:)) <3

def add(h):
    res=h+10
    return res

var=50*10

data = eval('add(var)')
print(data)

eval() 评估 的方法 expressions only. Thus, you can't use other statements。由于 import 是语句,因此不能在 eval().

中使用它

what are the other options (except using other file as module)

exec() 与导入一起工作,因此 exec()eval() 的组合工作:

var = 50 * 10
exec("import b")
data = eval("b.add(var)")
print(data)

甚至 exec() 没有 eval():

var = 50 * 10
exec("import b\ndata=b.add(var)")
print(data)

注:

  • IDE 可能会抱怨 data 在最新版本的代码中未定义
  • exec()eval()
  • 更危险