Python exec NameError

I have a string variable containing a function. the function is as follows:

def program():
    x[0] = y[1]
    z[0] = x[0]
    out = z[0]

This is the method:

def runExec(self, stringCode):
    x = [1,2,3,4]
    y = [5,6,7,8]
    z = [6,7,8,9]
    exec stringCode
    return out

I get a NameError, it seems that x, y and z are not available from execCode exec?

How can I make these variables available, do I need to somehow pass them?

thank

+3
source share
3 answers

Assuming you have a good reason to useexec , which is a premise that you should double check.

You need to provide global and local scope for the function exec. In addition, the line "program" should actually be executed instead of simply defining a function. This will work:

prog = """
x[0] = y[1]
z[0] = x[0]
out = z[0]
"""

def runExec(stringCode):
    x = [1,2,3,4]
    y = [5,6,7,8]
    z = [6,7,8,9]
    exec(stringCode, globals(), locals())
    return out

print runExec(prog)
+2
source

exec? , exec:

def program(x, y, z):
    x[0] = y[1]
    z[0] = x[0]
    out = z[0]
    return out

def runExec(self, func):
    x = [1,2,3,4]
    y = [5,6,7,8]
    z = [6,7,8,9]
    out = func(x, y, z)
    return out

self.runExec(program)
+2

.

global x,y,z
def runExec(self, func):
    x = [1,2,3,4]
    y = [5,6,7,8]
    z = [6,7,8,9]
    out = func(x, y, z)
    return out
+1

All Articles