How do I access all global variables inside a module (I don't who they are in advance)?
For example
file m.py:
def a(s):
exec('print '+s)
main code:
import m
x=2
m.a('x*2')
You want to use eval() here and not exec().
But what are you actually trying to do....the usage of eval() and exec() is in general bad style and in general not needed (especially scary when it comes to security considerations).
eval won't work here because print is a statement -- And anyway, eval doesn't have any way of knowing what x actually is unless you pass it globals and/or locals dictionaries.x in m.py, eval('x') in m.py will fail with a NameError.Why can't you just use (okay, if you seriously do have strings somehow, but then since it's almost all in code anyway, it just looks like you've got strings around it for some reason)
(re-written code):
file m.py:
def a(s):
print s
main code:
import m
x=2
m.a(x * 2)
You can hack it by directly importing the special __main__ module. In m.py:
def print_global(name):
import __main__
print getattr(__main__, name)
And in the main module:
import m
x = 2
m.print_global('x') # prints 2
While this example illustrates how to programatically work with the namespace, this is the kind of thing that should be done sparingly if at all.
m know what x is in the namespace of __main__?
exec()for stuff like this. It's not a good tool for the job. Likewise, globals are a bad idea in general - pass variables you need to the function.xinm.py...