[Tutor] Exec function problem

Alan Gauld alan.gauld at btinternet.com
Wed Sep 1 20:33:09 CEST 2010

"Currall, Andrew" <andrew.currall at aecom.com> wrote

> DemandModel.py is a valid, working python script. 
> If I create another script file, then:
> execfile('DemandModel.py')

You probably shouldn't. You should probably be importing it. 
Is there a reason why you want to use execfile()? 
Its nearly always the wrong solution...

> def runfile():
>     execfile('DemandModel.py')
> runfile()

>   File "DemandModel.py", line 12, in DemandModel
>     Parameters=ReadDmData(segname)
> NameError: global name 'ReadDmData' is not defined

So it works on a line by itself but not in a function?
And it is running the file but getting an undefined name. odd.
What happens if you run execfile() from a new interpreter prompt?

> CodeFile=open('DemandModel.py', 'r')
> exec(CodeFile)

What happens if you use import (assuming you store in 
somewhere in sys.path...)

Alan Gauld
Author of the Learn to Program web site

More information about the Tutor mailing list