Note that when you use atexit, you first need to register a function. I would recommend doing something similar to enforce an "atenter" functionality.
For example
# start of my code
atenter() # place 1
def main():
atenter() # place 2
# run main code
if __name__ == '__main__':
atenter() # place 3
main()
Place 2 seems like the place to go in most circumstances. The disadvantage of place 1 is that any file that imports your main function will accidentally call atenter. This will also cause problems if multiproecssing on some platforms. What does if __name__ == "__main__": do?
The problem with place 3 is that if you put a wrapper (like a "RunExamples" command line utility, or a GUI) on top of you main function in another file, atenter won't get called. It is probably enough to specify in the documentation that main shouldn't be called twice, though that could be enforced also.
If you're looking for something more elegant looking, you could create an "atenter" decorator, and wrap your main functions with it. Using the singleton pattern or something similar, you could make sure it only executes once, no matter how many times its called
There is an alternative approach. From the python docs
PYTHONSTARTUP
If this is the name of a readable file, the Python commands in that file are executed before the first prompt is displayed in
interactive mode. The file is executed in the same namespace where
interactive commands are executed so that objects defined or imported
in it can be used without qualification in the interactive session.
You can also change the prompts sys.ps1 and sys.ps2 in this file.
Modifying this environmental variable will let you execute a function, under the circumstances specified. This is not a good deployment strategy (it is contingent on several conditions being met on your local computer, including the mode python is being run in). However, it might more closely match what you're looking for and might be feasible if you have strong control over the python environment at deployment.