简体   繁体   English

如何获取exec的返回值?

[英]How to get return value of exec?

How would I do the following:我将如何执行以下操作:

>>> new=exec('i=100;2 if i > 4 else 3')
>>> repr(new)
'None'

I want to get 2 :我想得到2

>>> i=100
>>> 2 if i>4 else 3
2

I can do this with eval , as long as there isn't an assignment:只要没有分配,我就可以用eval做到这一点:

>>> new=eval('2 if i>4 else 3')
>>> new
2

In other words, how to execute a string of code (with an assignment, not just eval ) and get the last part?换句话说,如何执行一串代码(带有赋值,而不仅仅是eval )并获得最后一部分?


Here is a related question from ~5 years ago: not sure if the answers still apply though, or anything has changed since then: How do I get the return value when using Python exec on the code object of a function?这是大约 5 年前的一个相关问题:不确定答案是否仍然适用,或者从那以后发生了什么变化: How do I get the return value when using Python exec on the code object of a ZC1C425264E68385D1AB707?4 . .

You can pass a dict to be used for the global namespace.您可以传递要用于全局命名空间的dict Assign the result to a global variable and you can read it later.将结果分配给全局变量,您可以稍后读取它。

>>> data = {}
>>> exec('i=100;result = 2 if i > 4 else 3', data)
>>> data['result']
2

By default exec uses the module's namespace.默认情况下exec使用模块的命名空间。 If you don't mind the exec'd script's variables messing with your own variables, you could leave the global dict out.如果您不介意 exec'd 脚本的变量与您自己的变量相混淆,您可以将全局 dict 排除在外。

>>> exec('i=100;result = 2 if i > 4 else 3')
>>> result
2

You run the risk of accidentally overwriting data unexpectedly if you don't notice the use of a variable in the string.如果您没有注意到在字符串中使用了变量,您将冒着意外覆盖数据的风险。 But its certainly an option.但它肯定是一种选择。

You can also use 2 dictionaries, one for globals and one for locals and the variables you create will end up in the latter.您还可以使用 2 个字典,一个用于全局变量,一个用于局部变量,您创建的变量最终会出现在后者中。

>>> data1={}
>>> data2={}
>>> exec('i=100;result = 2 if i > 4 else 3', data1, data2)
>>> data2
{'i': 100, 'result': 2}

Notice that all of the variables you create in the executed script end up in the namespace dictionaries.请注意,您在执行的脚本中创建的所有变量最终都在命名空间字典中。

Just split on semicolon into two parts:只需将分号分成两部分:

exec('i=100')
new=eval('2 if i>4 else 3')

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

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