question regarding Guido's main article

Terry Reedy tjreedy at udel.edu
Thu Jun 3 13:32:50 EDT 2004


"Christopher Baus" <christopher at baus.net> wrote in message
news:4042.66.215.139.141.1086251805.squirrel at mail.baus.net...
>>> execfile("myscript.py")

This immediately called my main function, which should have only been
called if __name__ == "__main__".

What I expect was that __name__ would be something other than __main__
--------
When puzzled about a specific feature, look at the manual (if you didn't).
"
execfile(filename[,globals[,locals]])
...
The arguments are a file name and two optional dictionaries. The file is
parsed and evaluated as a sequence of Python statements (similarly to a
module) using the globals and locals dictionaries as global and local
namespace. If the locals dictionary is omitted it defaults to the globals
dictionary. If both dictionaries are omitted, the expression is executed in
the environment where execfile() is called. The return value is None.
"
The second to last sentence is the key.  In the environment you called
execfile in, __name__ == '__main__', and so thus it is.  In other words,
the effect of execfile is (almost) exactly the same as if you typed the
statements in interactively.

Terry J. Reedy







More information about the Python-list mailing list