【问题标题】:How to print pass arguments to code object via exec and print in python?如何通过exec打印将参数传递给代码对象并在python中打印?
【发布时间】:2016-12-30 23:43:27
【问题描述】:

如何通过 exec 将参数传递给代码对象并在 python 中打印?下面只是几个例子,看看事情在一般情况下是如何工作的。

def foo(x, y):
    return x * y

exec(foo.func_code {'x': 1, 'y': 5}) # This didn't work

def bar():
    return 3*5

exec(bar.func_code) # this got executed but I couldn't print it?

【问题讨论】:

  • exec('print(foo(1,5))')
  • 你为什么要这样做?为什么你需要准确地使用exec?我觉得有更好的方法来完成你想做的任何事情。

标签: python


【解决方案1】:

我认为不使用“黑魔法”就无法将参数传递给代码对象。为什么不使用exec("print foo(1, 5)")

在您的两个示例中,没有打印任何内容,因为exec 只是执行xxx.func_code,但函数foobar 不包含打印语句。

【讨论】:

  • 我知道它不包含打印语句,但为什么我们不能做一些更像 print (exec(code_object)) 或类似的事情,以及如何使用 code_object 和 exec 将参数传递给任何函数。这更多是我的意图。
  • exec(code_object)) return None,所以`print(exec(code_object))`是没有意义的。见Python: How to pass arguments to the code of a function?
  • @EmL 但从技术上讲,exec(foo.func_code, {'x': 1, 'y': 5}) 不是传递参数。
猜你喜欢
  • 1970-01-01
  • 2016-06-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-01-22
  • 1970-01-01
  • 1970-01-01
  • 2012-11-27
相关资源
最近更新 更多