How do I get the return value when using Python exec on the code object of a function?(在函数的代码对象上使用 Python exec 时如何获取返回值?)
问题描述
出于测试目的,我想直接执行在另一个函数内部定义的函数.
For testing purposes I want to directly execute a function defined inside of another function.
我可以通过父函数的代码(func_code)得到子函数的代码对象,但是当我执行它时,我没有得到返回值.
I can get to the code object of the child function, through the code (func_code) of the parent function, but when I exec it, i get no return value.
有没有办法从执行的代码中获取返回值?
Is there a way to get the return value from the exec'ed code?
推荐答案
是的,你需要在 exec 语句中进行赋值:
Yes, you need to have the assignment within the exec statement:
>>> def foo():
... return 5
...
>>> exec("a = foo()")
>>> a
5
这可能与您的情况无关,因为它被用于受控测试,但使用带有用户定义输入的 exec 时要小心.
This probably isn't relevant for your case since its being used in controlled testing, but be careful with using exec with user defined input.
这篇关于在函数的代码对象上使用 Python exec 时如何获取返回值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在函数的代码对象上使用 Python exec 时如何获取返回值?
基础教程推荐
- 使用生成器和迭代器时 Python 多循环失败 2022-01-01
- 在 Celery 工作人员中捕获 Heroku SIGTERM 以优雅地关 2022-01-01
- Discord.py 缺少必需的参数 2022-01-01
- pyserial - 可以从线程 a 写入串行端口,是否阻塞从线程 b 读取? 2022-01-01
- 用 Python 编写 Fortran 无格式文件 2022-01-01
- 尝试制作WhatsApp机器人 2022-01-01
- numpy float:比算术运算中内置的慢 10 倍? 2022-01-01
- 将 x 轴刻度更改为自定义字符串 2022-01-01
- 由Python将MP3转换为MIDI(类型错误:无法加载插件:mtg-Melodia:Melodia) 2022-01-01
- 与常规 dict 相比,Python manager.dict() 非常慢 2022-01-01
