简体   繁体   中英

Python exec NameError

I have a string variable containing a function. the function looks like this:

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

This is within a 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 am receiving a NameError, it seems x, y and z are not accessible from the stringCode exec ?

How can I make these variables accessible, do I have to pass them in some way ?

Thanks

Assuming you have a good reason to use exec , which is an assumption you should double-check.

You need to supply the global and local scope for the exec function. Also, the "program" string needs to actually run instead of just 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)

Why do you need to use exec ? The following code should work the same way, just without 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)

You can make them global.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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