D
D
Dmitry2012-10-26 23:32:18
Python
Dmitry, 2012-10-26 23:32:18

How to change external objects in the python code of the executable in exec()?

There is this code:

def executeRule(stdout, rule):
  obj = None
  try:
    parsedJson = json.loads(stdout)
    pyCmd = 'obj = parsedJson' + rule
    exec( pyCmd  )
  except BaseException as e:
    print( e, file=sys.stderr)
  return obj

Here:
rule is a string obtained from com arguments. lines sys.argv[2]
stdout is the output obtained as a result of launching the console tool. After parsing stdout,
I need to convert it into familiar data structures in python and get a value from them. The whole point is that I need to get on the basis of what was passed in the com. line.
The problem is that after exec() obj does not change and continues to be set to None. Although if you write code without exec, but directly, then the value is pulled out and it is in the parsed json!
How to organize a subject? What is the problem?
PS:
I'm starting to work on python Toko Toko

Answer the question

In order to leave comments, you need to log in

2 answer(s)
I
ILJICH, 2012-10-27
@EvilsInterrupt

In exec and eval, you can directly set global and local variables: eval(expression[, globals[, locals]])

>>> obj = None
>>> exec("obj = 2", {}, locals())
>>> print obj
2

V
Vitalik, 2012-10-27
@eXod

Correct, because exec is executed in a different namespace. Try like this:

obj = None
exec("""import random; global obj; obj = random.random(); obj *= 100;""")
print(obj)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question