Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
878 views
in Technique[技术] by (71.8m points)

python - 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:

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 i.e: ['has_at', 'has_num' ...]

Please let me know an alternative to exec() if possible in such a scenario.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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):

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

This code gives an error in 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).

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.

I hope somebody knows a good answer to the problem.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...