How to pass variables between scripts?

Marcelo Ramos mramos at montevideo.com.uy
Tue May 16 19:51:00 CEST 2006


Gross, Dorit (SDRN) escribió:
>>> #! /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
>
>
>   
If you print __name__ in second.py its value is '__builtin__', because 
of that your "main" doesn't execute.
Try adding this to test_exec.py before the execfile() call:

globvars[ '__name__' ] = '__main__'

It looks like a ad hoc fix but i couldn't find any doc about the change 
of __name__ to 'builtin' of a python script being run
from another with execfile().

Regards.

-- 
Marcelo Ramos
Fedora Core 5 | 2.6.16
Socio UYLUG Nro 125




More information about the Python-list mailing list