1

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)

Nikhil Gupta
  • 551
  • 10
  • 28
  • 1
    Cannot duplicate. Are you sure you're executing the file you think you are? – Ignacio Vazquez-Abrams Jan 14 '16 at 01:41
  • @IgnacioVazquez-Abrams Sorry, corrected the variable name to be `eventFileName` in `parent.py`. You should be able to run both files. But the point of the question is I am not able to use `experimentID` in `parent.py` which is originally populated in `parser.py`. – Nikhil Gupta Jan 14 '16 at 05:50

1 Answers1

4

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"])
Community
  • 1
  • 1
Jerzy
  • 670
  • 6
  • 12