467,161 Members | 1,011 Online
Bytes | Developer Community
Ask Question

Home New Posts Topics Members FAQ

Post your question to a community of 467,161 developers. It's quick & easy.

execfile in global scope

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

Aug 24 '05 #1
  • viewed: 5278
Share:
3 Replies
What about :

globdict= globals()

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

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

Aug 24 '05 #2
What about :

globdict= globals()

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

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

Aug 24 '05 #3
On 24 Aug 2005 01:50:25 -0700, v.*****@gmail.com wrote:
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

open('change.py','w').write("""\ ... x = 555
... """) print '%s\n%s%s' %('-'*30, open('change.py').read(), '-'*30) ------------------------------
x = 555
------------------------------ dir() ['__builtins__', '__doc__', '__name__'] x = 111
x 111 def changevar(): ... execfile('change.py', globals())
... x 111 changevar()
x

555

Regards,
Bengt Richter
Aug 24 '05 #4

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

2 posts views Thread by Jonathan | last post: by
2 posts views Thread by overly.crazy.steve@gmail.com | last post: by
1 post views Thread by Fernando Perez | last post: by
2 posts views Thread by Dave Westerman | last post: by
112 posts views Thread by istillshine@gmail.com | last post: by
1 post views Thread by moijes12 | last post: by
2 posts views Thread by Igor Kaplan | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.