简体   繁体   中英

python's execfile() variable scope issue

I have bunch of python scripts I am calling from a parent python script but I am facing trouble using the variables of the scripts I called in parent python script. Example of the scenario:

parent.py :

eventFileName = './0426_20141124T030101Z_NS3_T1outside-TEST-NS3.csv'
execfile('./parser.py')
print(experimentID) #I was hoping 0426 will be printed to screen but I am getting an error: global name 'experimentID' is not defined 

./parser.py :

fileNameOnly  = (eventFileName).split('/')[-1]
experimentID  = fileNameOnly.split('_')[0]

any suggestions? (The above is just an example of a case I am working on)

In brief, you can't just set/modify local variables in execfile() - from execfile() docs :

Note The default locals act as described for function locals() below: modifications to the default locals dictionary should not be attempted. Pass an explicit locals dictionary if you need to see effects of the code on locals after function execfile() returns. execfile() cannot be used reliably to modify a function's locals.

For a more comprehensive answer, see this .

If you really want to set global variable, you can call execfile() with an explicit globals argument as described in this answer :

eventFileName = './0426_20141124T030101Z_NS3_T1outside-TEST-NS3.csv'
execfile('./b.py', globals())
print experimentID

If you really are looking to set a variable which is local in parent.py , then you can pass explicitly a locals dictionary to execfile() :

eventFileName = './0426_20141124T030101Z_NS3_T1outside-TEST-NS3.csv'
local_dict = locals()
execfile('./b.py', globals(), local_dict)
print(local_dict["experimentID"])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM