How to terminate a main script?

Tal Einat taleinat at gmail.com
Wed Jul 12 07:05:02 EDT 2006


Helmut Jarausch wrote:
> Hi,
>
> I'm still looking for an elegant and clear means to
> terminate the main script in Python.
>
> Unfortunately, Python doesn't allow a 'return'
> instruction in the main script.
>
It is quite a common practice for Python scripts to define a main()
function which contains the actual code, and have "main()" on the last
line of the file. This allows you to just 'return' from wherever you
like in your code.

It is even more common to use this in the end instead of "main()":
if __name__ == "__main__":
    main()

This way, if the file is imported as a module, the main() function
won't execute, but if it is run directly from a command line or using
execfile() it will execute.

Enjoy!

- Tal




More information about the Python-list mailing list