Essentially I would like to define a handful of global Python functions in a script and ensure that they are loaded whenever I run a python script on my
machine, or whenever I start a Python terminal
Let's talk about your second option. There are ways to load functions and variables when you start a terminal. I'd recommend using IPython instead of the default Python terminal. However, to do this without installing IPython, modify the environment variable
PYTHONSTARTUP. You do lose the ability to compartmentalize your config files.
Once you install IPython, you'll need to initialize its configuration files.
To create the default profile:
ipython profile create
To address the common topic in the other answers, global variables and functions are a bad idea especially if they're implicitly defined. However, you can define and load separate config files when starting ipython.
To create such a profile:
ipython profile create <name>
To load the <name>
profile:
ipython --profile=<name>
Now to modify the config files. Run this command to see where they are:
ipython locate profile
You should find ipython_config.py
. I'd suggest reading it, it has very helpful comments.
But to get to the point, you can load arbitrary functions and variables when starting ipython by adding these lines to the config file:
c.InteractiveShellApp.exec_lines = [ "def p(s): print s" ]
c.InteractiveShellApp.exec_files = [ "/path/of/script.py" ]
I'm referencing the IPython docs and the comments in ipython_config.py
:
96 # List of files to run at IPython startup.
97 # c.TerminalIPythonApp.exec_files = []
98
99 # lines of code to run at IPython startup.
100 # c.TerminalIPythonApp.exec_lines = []