In Python, is there a similar thing like atexit. Atexit is meant to be used a "tear down". I need something like "set up". That before any script I run this setUp would be executed.
EDIT
I should have pointed out that I have several little scripts I execute separatelly. All of these scripts are connected to the same logic. I would like to introduce dependency injection into our project but e.g. python-inject needs to be configured before run of every script. I don't want to DRY myself setting at the beginning of all the scripts the same inject.configure(myConfiguration)
just to set it all up.
Now I am gonna have a look @en_Knight suggestion about PYTHONSTARTUP and then come back again.
SOLUTION What @en_Knight offered about PYTHONSTARTUP would work for sure. Although I have all the deploying power :] I feel it is not a good idea either. I solved my problem modifying sources of python-inject
Thank you for help!
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.