4

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

1
  • 3
    Why do you need to use exec? Commented May 11, 2012 at 12:15

3 Answers 3

4

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)
Sign up to request clarification or add additional context in comments.

Comments

1

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)

1 Comment

I need to use exec, it's not going to be the same code every time the code is being generated on the fly. The above is just an example.
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.