How to run script from interpreter?

Alex Martelli aleaxit at yahoo.com
Fri Jan 19 05:54:48 EST 2001


"Dan Rolander" <dan.rolander at marriott.com> wrote in message
news:mailman.979898969.13587.python-list at python.org...
> This doesn't work for me. I know how to import and how to use the if
> __name__ trick, but how can I execute a script from the interactive Python
> interpreter? That is, can I load a script and have it run from inside the
> interpreter? (I'm sure this is easy I'm just not seeing it.)

Suppose you have, somewhere on the path Python searches, a
file foo.py containing the single Python statement:

print "I'm being executed"

When, at the interactive interpreter prompt, you type an import
statement:

>>> import foo
I'm being executed
>>>

module foo.py has been loaded and, since this was the first time
it was imported in this session, its module-level code was executed.

Another import statement will NOT repeat execution of the module's
code...:

>>> import foo
>>>

No execution in this case, because it was not the first import
in this session!

You can, however, force such re-execution by reloading the
module object after having imported it:

>>> reload(foo)
I'm being executed
<module 'foo' from 'foo.pyc'>
>>>

The reload function also returns the new module-object, which
is why we see this second line here (the interpreter is showing
it to us) -- if you don't want this little bother just assign it:

>>> _=reload(goo)
I'm being executed
>>>


Alex






More information about the Python-list mailing list