1: print(">1") if customCode != "": exec(c...">

Problems with Python exec ()

I had this code:

def test(variable, customCode = ""):

    if variable > 1:
        print(">1")

    if customCode != "":
        exec(customCode)

    if foo == 1:
        print("Success")

numb = 12
code = "if variable > 1: foo = 1"

test(numb, code)

What on execution gives this error:

Error 1

So, I added foo = 0at the beginning of the code and got this output:

Issue 2

Now, obviously, it should also output Success, but it is not.

What is the problem?

Using Python 3.

+1
source share
2 answers

The correct way is to pass dict exec in python 3 and do a key search, in python2 your code will work as it is, because exec is an operator, not a function in python3:

def test(variable, customCode = ""):
    d = {"variable":variable}
    if customCode != "":
        exec(customCode, d)
    if d["foo"] == 1:
        print("Success")

numb = 12
code = "if  variable > 1: foo = 1"

test(numb, code)

Exit:

In [13]: numb = 12

In [14]: code = "if  variable > 1: foo = 1"

In [15]: test(numb, code)
Success

Exec

. , locals(): . locals, localals exec().

, if variable > 1 False, , foo .

+6

@Padraic Cunningham , :

: , : foo = 1, do : global foo; foo = 1.

:

def test(variable, customCode = ""):

    if variable > 1:
        print(">1")

    if customCode != "":
        exec(customCode)

    if foo == 1:
        print("Success")

numb = 12
code = "if variable > 1: global foo; foo = 1"

test(numb, code)

, exec() - , Python 3, foo . (: @Padraic Cunningham)

0

Source: https://habr.com/ru/post/1606879/


All Articles