execfile in global scope

V

v.vayer

I need to execfile() from a function in order to set value for a global
variable from inside the executed file. I know there are "globals" and
"locals" optional arguments for execfile, but I just can't figure out
how to use them correctly. Here is an example:

Change.py
=========
x = 555

Main.py
=======

def changevar():
execfile("change.py")

x = 111 # global var
changevar()
print x # returns 111 instead of 555
 
T

tooper

What about :

globdict= globals()

def changevar():
global globdict
execfile("changevar.py",globdict)

x = 111 # global var
changevar()
print x # returns 111 instead of 555
 
T

tooper

What about :

globdict= globals()

def changevar():
global globdict
execfile("changevar.py",globdict)

x = 111 # global var
changevar()
print x # returns 111 instead of 555
 
B

Bengt Richter

I need to execfile() from a function in order to set value for a global
variable from inside the executed file. I know there are "globals" and
"locals" optional arguments for execfile, but I just can't figure out
how to use them correctly. Here is an example:

Change.py
=========
x = 555

Main.py
=======

def changevar():
execfile("change.py")
execfile("change.py", globals()) # the builtin globals function returns
# the current module's global namespace
# as a writable dict
x = 111 # global var
changevar()
print x # returns 111 instead of 555
... x = 555
... """) ------------------------------
x = 555
------------------------------
>>> dir() ['__builtins__', '__doc__', '__name__']
>>> x = 111
>>> x 111
>>> def changevar():
... execfile('change.py', globals())
... 555

Regards,
Bengt Richter
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,776
Messages
2,569,603
Members
45,197
Latest member
Sean29G025

Latest Threads

Top