简体   繁体   English

如何在 python 的变量中使用代码?

[英]How can i use code in a variable in python?

I tried with exec() but it doesn't work for what i'm trying to do:我尝试使用exec()但它不适用于我想要做的事情:

math = "1 + 1"
a = exec(math)
print(a)

when "a" is printed i get当打印“a”时,我得到

None

how can i do something like this?我怎么能做这样的事情?

exec("a = 1 + 1")
print(a)
2
b = eval("1 + 1")
print(b)
2

You're getting None because exec always returns None , instead it execute the expression.你得到None因为exec总是返回None ,而不是执行表达式。 What you might want is eval , it returns whatever is evaluated inside.您可能想要的是eval ,它返回内部评估的任何内容。

Notice that both of them are quite dangerous as malicious programs can easily assess your data by input.请注意,它们都非常危险,因为恶意程序可以通过输入轻松评估您的数据。

Why is using 'eval' a bad practice? 为什么使用“评估”是一种不好的做法?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM