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)

2
  • 1
    Cannot duplicate. Are you sure you're executing the file you think you are? Commented Jan 14, 2016 at 1: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. Commented Jan 14, 2016 at 5:50

1 Answer 1

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"])
Sign up to request clarification or add additional context in comments.

1 Comment

Perfect. Works great :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.