How to pass variables between scripts?

Gross, Dorit (SDRN) Dorit.Gross at fao.org
Mon May 15 15:29:13 CEST 2006


> >
> > #! /usr/local/bin/python
> > # test_exec.py
> >
> > import os, sys, glob
> >
> > fileList = glob.glob('/data/*.ZIP')
> >
> > for f in fileList:
> > 	try: 
> > 		globvars = {'infile' : f}
> > 		locvars = {}
> > 		execfile('/scripts/second.py', globvars(), locvars)
> > 	except IOError:
> > 		exit(0)
> > 	print locvars
> >
> >
> 
> You are calling the dictionary globvars as a function then the error. 
> The fixed line is:
> 
> execfile('/scripts/second.py', globvars, locvars)
> 
> 
> 
> What you want is the function globals().
> Try putting this line in second.py:
> 
> print globals()['infile']
> 
> Using the dictionary returned by globals() you can make second.py to 
> read the contents of testexec.py's globvars dictionary.
> locvars is populated with the local variables of second.py 
> and that is 
> what you want.
> 

Marcelo, thank you! Passing the variables with dictonaries and function
globals() works fine if no other functions are defined in 'second.py'. Now
'second.py' contains further functions and a "if __name__ = __main__"
statement and in this case it seems that 'second.py' is not fully executed
from 'test_exec.py'. For the sole purpose of testing, 'second.py' looks like
this at the moment:

#! /usr/local/bin/python
# second.py

import os, sys

global zipfile
print 'Read from globals: ' + globals()['infile']
zipfile = globals()['infile']
print 'Read from zipfile: ' + zipfile

if __name__ == '__main__':

	print 'Hello'
	print globals()['infile']
	print zipfile

	
Calling test_exec.py results into this output:

 ./test_exec.py 
Read from globals: /data/S0012230_0010.ZIP
Read from zipfile: /data/S0012230_0010.ZIP


It seems that the commands within the main are not executed when calling
test_exec.py!?! Is there a way to make it running?

Regards and thank you again, 
Dorit



More information about the Python-list mailing list