Re: executing the contents of a file

Guido.van.Rossum@cwi.nl
Tue, 10 Jan 1995 11:24:09 +0100

> Is there some way for a running python program to execute the
> contents of a file, similar to "consult" in Prolog. I have a
> running program which has instantiated objects a, b, and c and
> I would like to load a file F which contains statements like,
>
> a.do_some_action(....)
> b.do_some_other_action(...)

Yes -- try the built-in function execfile(). It does exactly what you
want. Unfortunately it isn't documented in 1.1 -- an oversight that
occurs at times... Here's a section to be inserted into libfuncs.tex:

function -- execfile(file[, globals[, locals]])

\begin{funcdesc}{execfile}{file\optional{\, globals\optional{\, locals}}}
This function is similar to the \code{eval()} function or the
\code{exec} statement, but parses a file instead of a string. It is
different from the \code{import} statement in that it does not use
the module administration -- it reads the file unconditionally and
does not create a new module.

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 \var{globals} and \var{locals}
dictionaries as global and local name space. If the \var{globals}
dictionary is omitted it defaults to the \var{locals} dictionary.
If both dictionaries are omitted, the expression is executed in the
environment where \code{execfile} is called. The return value is
None.
\end{funcdesc}

--Guido van Rossum, CWI, Amsterdam <mailto:Guido.van.Rossum@cwi.nl>
<http://www.cwi.nl/cwi/people/Guido.van.Rossum.html>