Failure of running a second script in same interactive session

Steven D'Aprano steven at REMOVE.THIS.cybersource.com.au
Tue Apr 21 02:33:30 EDT 2009


On Mon, 20 Apr 2009 23:52:39 -0500, pdlemper wrote:

> When I open python.exe to the console or "interactive window" and
> import/run a script I am frustrated trying to import and run another
> script in the same session.  eg I run the script alphasort once fine :
>>>> import alphasort                 < it runs >

You are confused by the difference between *importing* a module and 
*running* a script. They are not necessarily the same thing, although 
some modules may be usable as scripts.


Try creating a script with this single line:

print("This runs once.")


Now import that file. The *first* time you import it, the module has to 
be executed, and it will print "This runs once." as you expect. But the 
next time you import it, the module is already initialized and stored in 
the cache and nothing will print. This is by design.

To run the module again, you can:

* exit the interpreter, clearing the cache, and then start again.

* or you can run by giving it as an argument to python.exe

(On Linux I'd say "python name_of_script.py" but I'm not sure how you 
would do that under Windows.)


The best way to do what you want to do is when you write a script, create 
a "main function". Here's an example:


print("Initialization code is here")

def main():
    print("Doing stuff here")


Everything outside of main() will be run *once* only, the first time you 
import it. To run the script, do this:

>>> import script
Initialization code is here
>>> script.main()
Doing stuff here
>>> import script  # not necessary, because it is already imported
>>> script.main()
Doing stuff here



Notice that there is nothing special about the name "main". You can call 
it anything you like.


Now for the special Python magic: when you run a Python script from the 
regular Linux or Windows command line (not the Python interpreter), it 
does something special. You can add this to the bottom of your script:

if __name__ == '__main__':
    main()


and now it will automatically call main() whenever you run the script.

Hope this helps.



-- 
Steven.



More information about the Python-list mailing list