简体   繁体   English

exec() 在 function python3.x 中不起作用

[英]exec() not working inside function python3.x

I am trying to run this code but it seems that the exec() is not executing the string inside the function:我正在尝试运行此代码,但似乎exec()没有执行 function 中的字符串:

def abc(xyz):
    for i in fn_lst:
        s = 'temp=' + i + '(xyz)'
        exec(s)
        print (temp)

abc('avdfbafadnf')

The error I am receiving:我收到的错误:

NameError                                 Traceback (most recent call last)
<ipython-input-23-099995c31c78> in <module>()
----> 1 abc('avdfbafadnf')

<ipython-input-21-80dc547cb34f> in abc(xyz)
      4         s = 'temp=' + i + '(word)'
      5         exec(s)
----> 6         print (temp)

NameError: name 'temp' is not defined

fn_lst is a list of function names ie: ['has_at', 'has_num'...] fn_lst是 function 名称的列表,即: ['has_at', 'has_num'...]

Please let me know an alternative to exec() if possible in such a scenario.在这种情况下,如果可能的话,请让我知道exec()的替代方案。

To make a variable set by the string passed to exec(), available outside of the call, use exec() like this:要使由传递给 exec() 的字符串设置的变量在调用之外可用,请像这样使用 exec():

exec( a_string, globals(), locals() )

For example,例如,

exec( 'a = 3', globals(), locals() )

print( a )

will print the following result:将打印以下结果:

3

Note: In this example it would have been sufficient to use locals() alone, ie omitting globals().注意:在这个例子中,单独使用 locals() 就足够了,即省略 globals()。 Both were included here to illustrate the more general case.两者都包含在此处以说明更一般的情况。 The use of locals() and/or globals() is part of a larger topic, known as "Scope". locals() 和/或 globals() 的使用是一个更大的主题的一部分,称为“范围”。 You can read more about this at Python Textbook - Scope您可以在Python Textbook - Scope 中阅读更多相关信息

I don't have enough reputation points to add comments, but I would like to mention that the previous answer by DrM does not work (inside a function):我没有足够的声望点来添加评论,但我想提一下 DrM 之前的答案不起作用(在函数内):

def test():
    exec( 'a = 3', globals(), locals() )
    print(a)
test()

This code gives an error in Python 3:这段代码在 Python 3 中给出了一个错误:

NameError: name 'a' is not defined

I tried some methods using the compile function suggested in other forums, but they still do not work for me (at least with the options I have seen mentioned).我尝试了一些使用其他论坛中建议的compile函数的方法,但它们仍然对我不起作用(至少对于我所看到的选项)。

According to my research, this the closest code that I have seen working:根据我的研究,这是我见过的最接近的代码:

def test():
    lcls = locals()
    exec( 'a = 3', globals(), lcls )
    a = lcls["a"]
    print(f'a is {a}')
test()

It successfully prints:它成功打印:

a is 3

I think this is an important topic overall.我认为这是一个重要的整体话题。 Sometimes when you work with symbolic algebra libraries, like Sympy, defining variables though the exec function can be very convenient for Scientific Computing.有时,当您使用符号代数库(如 Sympy)时,通过exec函数定义变量对于科学计算来说非常方便。

I hope somebody knows a good answer to the problem.我希望有人知道这个问题的好答案。

After spending so much time doing hit and trial on this problem, I can say that using exec like this was working without any problem inside function, otherwise it threw error.在花了这么多时间来解决这个问题之后,我可以说像这样使用 exec 在函数内部没有任何问题,否则它会抛出错误。 I have tested this for both functions and variables.我已经对函数和变量进行了测试。

def main():
  x = "def y():\n\treturn('This will work')"
  #pass only globals() not locals()
  exec(x,globals())
  print(y())
  
main()

def test():
    #pass only globals() not locals()
    exec( 'a = 3', globals())
    print(a)
test()

Here is a screenshot of this working on W3School's online interpreter (you can copy/paste and test it here yourself)这是在W3School 的在线解释器上工作的屏幕截图(您可以在此处复制/粘贴并自行测试) 在此处输入图片说明

Instead of using exec with function names, just keep the function objects in the list:不要将exec与函数名称一起使用,只需将函数对象保留在列表中:

fn_lst = [has_at, has_num, ...]

and perform the call directly :直接执行呼叫:

def abc(xyz):
    for i in fn_lst:
        temp= i(xyz)
        print(temp)

I search this problem because I tried to import variables of a configuration file into a function, but it failed.我搜索这个问题是因为我试图将配置文件的变量导入 function,但它失败了。

After some trial, I got following conclusions:经过一番试验,我得出以下结论:

  1. globals()['a']=1 can change global variables. globals()['a']=1 可以改变全局变量。
  2. locals()['a']=1 cannot change local variables in current scope, unless current scope is "main", where id(locals())==id(globals()). locals()['a']=1 不能改变当前 scope 中的局部变量,除非当前 scope 是“main”,其中 id(locals())==id(globals())。

This is why exec() for locals() works in "main" scope, but doesn't work inside a function.这就是为什么 exec() for locals() 在“main”scope 中有效,但在 function 中无效的原因。

I think this is a trap of python's scope mechanism.我认为这是python的scope机制的陷阱。

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

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